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!
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”:
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?
You’re right! I’ve now updated the snippet, it should work for variable products as well
Hello,
Similar but different logic, but is not working( Woocommerce 7.5.1 ), Please see the code below.
Thanks
Thank you Ishor
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
Hey Nick! This code only triggers for logged out customers, and reduces the price by 20%. Does this help?
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.
Did you copy/paste the exact snippet, including the comments?
Thank you
Welcome
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 .
Yes you can!
I have same question, Can you explain or any refferance to do that . Please
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
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 ๐
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
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
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!
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:
– 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!
Hey Alex! Try with https://www.businessbloomer.com/woocommerce-bulk-dynamic-pricing-without-a-plugin/
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
Yes, it changes the price to all products
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?
I don’t use the mini-cart so while coding I probably forgot this part. You’d need another snippet for that
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:
I’ve tried filtering woocommerce_cart_item_price but not having much luck for some reason. Any thoughts?
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!
Great!
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?
Oh, and actually pass a specific price from the product page to the cart?
Hey Stephanie, I suggest you take a look at “conditional logic”: https://businessbloomer.com/woocommerce-conditional-logic-ultimate-php-guide/. Enjoy ๐
i want to display product price 199INR for indian customer and 5USD for other country. How can i implement this logic in woocommerce.
https://aelia.co/shop/prices-by-country-woocommerce/
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?
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!
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.
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!
Hi Mark,
You should be able to do this by wrapping the relevant function execution in conditionals using
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