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.

Note: this is now compatible with Simple and Variable products.

/**
 * @snippet       Alter Product Pricing Part 1 - WooCommerce Product
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 8
 * @community     https://businessbloomer.com/club/
 */

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

function bbloomer_alter_price_display( $price, $product ) {
	
    // ONLY ON FRONTEND
    if ( is_admin() ) return $price;
	
    // ONLY IF PRICE NOT NULL
    if ( '' === $product->get_price() ) return $price;
	
    // IF CUSTOMER LOGGED IN, APPLY 20% DISCOUNT	
    if ( wc_current_user_has_role( 'customer' ) ) {
        if ( $product->is_type( 'simple' ) || $product->is_type( 'variation' ) ) {			
			if ( $product->is_on_sale() ) {
				$price = wc_format_sale_price( wc_get_price_to_display( $product, array( 'price' => $product->get_regular_price() ) ) * 0.80, wc_get_price_to_display( $product ) * 0.80 ) . $product->get_price_suffix();
			} else {
				$price = wc_price( wc_get_price_to_display( $product ) * 0.80 ) . $product->get_price_suffix();
			}			
		} elseif ( $product->is_type( 'variable' ) ) {
			$prices = $product->get_variation_prices( true );
			if ( empty( $prices['price'] ) ) {
				$price = apply_filters( 'woocommerce_variable_empty_price_html', '', $product );
			} else {
				$min_price = current( $prices['price'] );
				$max_price = end( $prices['price'] );
				$min_reg_price = current( $prices['regular_price'] );
				$max_reg_price = end( $prices['regular_price'] );
				if ( $min_price !== $max_price ) {
					$price = wc_format_price_range( $min_price * 0.80, $max_price * 0.80 );
				} elseif ( $product->is_on_sale() && $min_reg_price === $max_reg_price ) {
					$price = wc_format_sale_price( wc_price( $max_reg_price * 0.80 ), wc_price( $min_price * 0.80 ) );
				} else {
					$price = wc_price( $min_price * 0.80 );
				}
				$price = apply_filters( 'woocommerce_variable_price_html', $price . $product->get_price_suffix(), $product );
			}
		}		
    }
	
    return $price;

}

/**
 * @snippet       Alter Product Pricing Part 2 - WooCommerce Cart/Checkout
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 8
 * @community     https://businessbloomer.com/club/
 */

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 custom code?

You should place custom PHP in functions.php and custom CSS in style.css of your child theme: where to place WooCommerce customization?

This code still works, unless you report otherwise. To exclude conflicts, temporarily switch to the Storefront theme, disable all plugins except WooCommerce, and test the snippet again: WooCommerce troubleshooting 101

Related content

  • WooCommerce Visual Hook Guide: Single Product Page
    Here’s a visual hook guide for the WooCommerce Single Product Page. This is part of my “Visual Hook Guide Series“, through which you can find WooCommerce hooks quickly and easily by seeing their actual locations (and you can copy/paste). If you like this guide and it’s helpful to you, let me know in the comments! […]
  • WooCommerce: Disable Variable Product Price Range $$$-$$$
    You may want to disable the WooCommerce variable product price range which usually looks like $100-$999 when variations have different prices (min $100 and max $999 in this case). With this snippet you will be able to hide the highest price, and add a “From: ” prefix in front of the minimum price. At the […]
  • WooCommerce: Hide Price & Add to Cart for Logged Out Users
    You may want to force users to login in order to see prices and add products to cart. That means you must hide add to cart buttons and prices on the Shop and Single Product pages when a user is logged out. All you need is pasting the following code in your functions.php (please note: […]
  • WooCommerce: How to Fix the “Cart is Empty” Issue
    For some reason, sometimes you add products to cart but the cart page stays empty (even if you can clearly see the cart widget has products in it for example). But don’t worry – it may just be a simple cache issue (and if you don’t know what cache is that’s no problem either) or […]
  • WooCommerce: “You Only Need $$$ to Get Free Shipping!” @ Cart
    This is a very cool snippet that many of you should use to increase your average order value. Ecommerce customers who are near the “free shipping” threshold will try to add more products to the cart in order to qualify for free shipping. It’s pure psychology. Here’s how we show a simple message on the […]

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. Follow @rmelogli

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

  1. First off.. you are the best resource for WordPress/WooCommerce code snippets on the entire http://www... hands down. I appreciate the clear and concise presentation and the fact they are applied to real world business logic.

    On this.. works great.. except for variable products.. on the product grid and the product single.. for the price it is showing “0.00” — when I choose a variation, price shows correctly with that variation – any thoughts on why this is happening?

    1. You’re right! I’ve now updated the snippet, it should work for variable products as well

  2. Hello,

    Similar but different logic, but is not working( Woocommerce 7.5.1 ), Please see the code below.

    add_action( 'woocommerce_before_calculate_totals', 'set_item_cart_prices', 20, 1 );
    function set_item_cart_prices( $cart ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
            return;
    
        // Loop through cart items
        foreach ( $cart->get_cart() as $cart_item ){
            if( ! is_user_logged_in() ){
                $cart_item['data']->set_price( $cart_item['data']->get_regular_price() );
            }
        }
    }
    

    Thanks

  3. Hi Rodolfo,

    First up I really appreciate the value your site provides to the WooCommerce community. It’s been a go-to resource of mine for years. I have only just found out about the BloomerArmada will be signing up.

    I have just tested this code snippet on WooCommerce 7.4 and it doesn’t seem to be working. I have also tried using the default 2023 theme and a custom theme I’ve developed with the same results.

    I have ensured the product has a price and SKU. Is there anything else I might be missing? If I can get this working it will solve a huge challenge for me.

    Thank you,
    Nick

    1. Hey Nick! This code only triggers for logged out customers, and reduces the price by 20%. Does this help?

  4. 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?

  5. Thank you

  6. 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

  7. 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

  8. 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!

  9. 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!

  10. 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

  11. 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

  12. 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!

  13. 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 ๐Ÿ™‚

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

  15. 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!

  16. 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? Customization? Leave your comment now!
_____

If you are writing code, please wrap it like so: [php]code_here[/php]. Failure to complying with this, as well as going off topic or not using the English language will result in comment disapproval. 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 the Business Bloomer Club to get quick WooCommerce support. Thank you!

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