WooCommerce: Set / Override Product Price Programmatically

There are times when the edit product page settings are not enough. Yes, you usually set regular and sale price via the price fields under “Product Data”; however sometimes you may have to override those prices via code, because you’re running a special promotion, you don’t want to manually change thousands of prices or maybe you need to show different values to logged in customers only.

Either way, “setting” the product price programmatically consists of two distinct operations. First, you need to change the “display” of the product price on single and loop pages; second, you actually need to set a “cart item” price, because the previous code does not really alter price values.

As usual, easier coded than said, so let’s see how it’s done. Enjoy!

This is a screenshot of the single product page after applying the 20% discount to logged in customers only. Original price was $34

PHP Snippet: Alter Product Price Programmatically @ WooCommerce Frontend

For example, in the snippet below we will change the price of a product ID only if the user is logged in and is a registered customer. Of course you can apply the same strategy to different case scenarios e.g. change prices for a specific product category, apply a surcharge to all products below $10, and so on. Applications are endless.

/**
 * @snippet       Alter Product Pricing Part 1 - WooCommerce Product
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 4.1
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */

add_filter( 'woocommerce_get_price_html', 'bbloomer_alter_price_display', 9999, 2 );

function bbloomer_alter_price_display( $price_html, $product ) {
	
    // ONLY ON FRONTEND
    if ( is_admin() ) return $price_html;
	
    // ONLY IF PRICE NOT NULL
    if ( '' === $product->get_price() ) return $price_html;
	
    // IF CUSTOMER LOGGED IN, APPLY 20% DISCOUNT	
    if ( wc_current_user_has_role( 'customer' ) ) {
        $orig_price = wc_get_price_to_display( $product );
        $price_html = wc_price( $orig_price * 0.80 );
    }
	
    return $price_html;

}

/**
 * @snippet       Alter Product Pricing Part 2 - WooCommerce Cart/Checkout
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 4.1
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */

add_action( 'woocommerce_before_calculate_totals', 'bbloomer_alter_price_cart', 9999 );

function bbloomer_alter_price_cart( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;

    // IF CUSTOMER NOT LOGGED IN, DONT APPLY DISCOUNT
    if ( ! wc_current_user_has_role( 'customer' ) ) return;

    // LOOP THROUGH CART ITEMS & APPLY 20% DISCOUNT
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
        $product = $cart_item['data'];
        $price = $product->get_price();
        $cart_item['data']->set_price( $price * 0.80 );
    }

}

And here’s the screenshot of the same product, in logged-out mode. This shows the original product price ($34) as per the WooCommerce settings. It displays for all non logged in users and also for all logged in users who are not “customers”:

Where to add this snippet?

You can place PHP snippets at the bottom of your child theme functions.php file (delete "?>" if you have it there). CSS, on the other hand, goes in your child theme style.css file. Make sure you know what you are doing when editing such files - if you need more guidance, please take a look at my free video tutorial "Where to Place WooCommerce Customization?"

Does this snippet (still) work?

Please let me know in the comments if everything worked as expected. I would be happy to revise the snippet if you report otherwise (please provide screenshots). I have tested this code with Storefront theme, the WooCommerce version listed above and a WordPress-friendly hosting on PHP 7.3.

If you think this code saved you time & money, feel free to join 14,000+ WooCommerce Weekly subscribers for blog post updates or 250+ Business Bloomer supporters for 365 days of WooCommerce benefits. Thank you in advance :)

Need Help with WooCommerce?

Check out these free video tutorials. You can learn how to customize WooCommerce without unnecessary plugins, how to properly configure the WooCommerce plugin settings and even how to master WooCommerce troubleshooting in case of a bug!

Rodolfo Melogli

Business Bloomer Founder

Author, WooCommerce expert and WordCamp speaker, Rodolfo has worked as an independent WooCommerce freelancer since 2011. His goal is to help entrepreneurs and developers overcome their WooCommerce nightmares. Rodolfo loves travelling, chasing tennis & soccer balls and, of course, wood fired oven pizza.

31 thoughts on “WooCommerce: Set / Override Product Price Programmatically

  1. I copied the code into a code snippet. At activation I got an error “syntax error, unexpected identifier “add_filter” at line 9″.
    It’s on the current WordPress Version 6.1.1 and PHP 7.4 is running.

    1. Did you copy/paste the exact snippet, including the comments?

  2. Thank you

  3. Thanks for your Valuable information. I have a WooCommerce website and 10000 products, Can I update all product’s sale price 5% by database ? please .

      1. I have same question, Can you explain or any refferance to do that . Please

        1. Yes, what I meant is that you don’t need to edit the DB, this code can edit the price “on the go” for all your products if you wish

  4. Hi Rodolfo, can you please explain what “if ( did_action( ‘woocommerce_before_calculate_totals’ ) >= 2 )” mean and why it should be added to the function? Is it mandatory to add?
    Thanks in advance ๐Ÿ™‚

    1. Great question! It’s optional. Some other plugins that alter prices *may* hook into woocommerce_before_calculate_totals, so with that call we avoid that the price changes again. But if you have no other plugins, you can remove it

  5. Hi, i am stuck in the situation. I have added one toggle button to include exclude tax on single product page. Once user click it will add tax to product price. (By your provided hook/logic).

    But I want to implement this add_filter(‘woocommerce_get_price_html’) using ajax to change prices without page refresh.

    Because on this price we are doing some other calculations by js. So can’t load page everytime on click of tax. Its removing our js calculations based on price.

    Please help me with this query, its a bit urgent for me.

    Thanks,
    Robin H

    1. Hi Robin, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  6. Thank you so much for your hard work! Your site has helped me out a lot of times in difficult situations.
    Please tell me, is it possible to modify your code above so that the displayed price of the product changes when the quantity changes?
    In other words, so that a specific product with id 648 changes the displayed price if you increase its quantity?
    Roughly speaking:

    if ($product_id = 648 && $quantity >= 2)

    – the displayed regular price changes to another one.
    I’ve already dug all over Google, but I haven’t found anything concrete ๐Ÿ™
    Thank you in advance!

  7. the problem that i see is that this code is executed on every price is showed on that page…
    so if i have for example, related products on the bottom of the page. they will change the price too

    1. Yes, it changes the price to all products

  8. There seems to be a bug with this code and the minicart.
    It doesn’t update the price for the line items in the minicart. The product page, cart page and checkout are all fine, it’s just the minicart line items that show the incorrect price. I’ve checked on Storefront and it is still happening > https://prnt.sc/uvdeps

    Any ideas why it’s not updating the minicart?

    1. I don’t use the mini-cart so while coding I probably forgot this part. You’d need another snippet for that

  9. Works almost perfectly–the exception being that WooCommerce still displays the original price in the minicart for some reason. I checked my theme and the minicart template appears to output the price the same way as the WooCommerce core template file:

    $product_price = apply_filters( 'woocommerce_cart_item_price', WC()->cart->get_product_price( $_product ), $cart_item, $cart_item_key );

    I’ve tried filtering woocommerce_cart_item_price but not having much luck for some reason. Any thoughts?

    1. Upon further investigation, the issue seemed to be that the minicart data is not calculated on-the-fly, so it was just calling up the original price from when I’d added it to my cart. Deleting and re-adding the item to my cart displays the modified price as expected.

      Curious, but I guess I can live with it… Thanks for the code!

      1. Great!

  10. All the example I see are related to apply a discount or a new price to ALL the items in the cart/site. Is it doable to target only one item?

    1. Oh, and actually pass a specific price from the product page to the cart?

      1. Hey Stephanie, I suggest you take a look at “conditional logic”: https://businessbloomer.com/woocommerce-conditional-logic-ultimate-php-guide/. Enjoy ๐Ÿ™‚

  11. i want to display product price 199INR for indian customer and 5USD for other country. How can i implement this logic in woocommerce.

  12. How can I apply this code for different roles and have the discount take it from a field saved in the product database as custom field meta?

    1. Hi Nando, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  13. This is kind of what I am trying to do except I need if role is customer or logged out they get regular price and if role after login is Dealer they get the sale price. Our prices are not standard where I can use any of the formula systems so we just want to use the two pricing fields already in woocommerce.

    1. Hi Mark, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

      1. Hi Mark,

        You should be able to do this by wrapping the relevant function execution in conditionals using

         if( current_user_can('dealer') ) {
        #your code
        }
        

        As Rodolfo mentioned if your uncomfotable with this then you should contact him or another professional WordPress/WooCommerce developer to help you with you exact requirements.

        Cheers,

        Jonny

Questions? Feedback? Support? Leave your Comment Now!
_____

If you are writing code, please wrap it between shortcodes: [php]code_here[/php]. Failure to complying with this (as well as going off topic, not writing in English, etc.) will result in comment deletion. You should expect a reply in about 2 weeks - this is a popular blog but I need to get paid work done first. Please consider joining BloomerArmada to get blog comment reply priority, ask me 1-to-1 WooCommerce questions and enjoy many more perks. Thank you :)

Your email address will not be published. Required fields are marked *