
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 need to set a “cart item” price, because the previous code does not 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.
add_filter( 'woocommerce_get_price_html', 'phpsof_alter_price_display', 9999, 2 ); function phpsof_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; } add_action( 'woocommerce_before_calculate_totals', 'phpsof_alter_price_cart', 9999 ); function phpsof_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”:
