How to display single price for WooCommerce variable products? (Code Snippet)

When you apply a discount to variable products, by default, WooCommerce shows the price range on the product page by taking the lowest and highest variable prices. With the help of the given code snippet, you can now display a single price for variable products. The code snippet is not only limited to ELEX plugins but can be used on any WordPress store running WooCommerce.

The displaying single price will be the lowest price of the product variation.

Code snippet to display a single price for WooCommerce variable products

If you need to remove the price range and add a single price on the product page of the variable products, use the below code snippet.

Before configuring the code snippet, the price will be displayed on the product page of variable products as in the below screenshot.

showing price range of variable products

Check the code snippet:

//Hide Price Range for WooCommerce Variable Products
add_filter( 'woocommerce_variable_sale_price_html',
'lw_variable_product_price', 10, 2 );
add_filter( 'woocommerce_variable_price_html',
'lw_variable_product_price', 10, 2 );

function lw_variable_product_price( $v_price, $v_product ) {

// Product Price
$prod_prices = array( $v_product->get_variation_price( 'min', true ),
                            $v_product->get_variation_price( 'max', true ) );
$prod_price = $prod_prices[0]!==$prod_prices[1] ? sprintf(__('%1$s', 'woocommerce'),
                       wc_price( $prod_prices[0] ) ) : wc_price( $prod_prices[0] );

// Regular Price
$regular_prices = array( $v_product->get_variation_regular_price( 'min', true ),
                          $v_product->get_variation_regular_price( 'max', true ) );
sort( $regular_prices );
$regular_price = $regular_prices[0]!==$regular_prices[1] ? sprintf(__('%1$s','woocommerce')
                      , wc_price( $regular_prices[0] ) ) : wc_price( $regular_prices[0] );

if ( $prod_price !== $regular_price ) {
$prod_price = '<del>'.$regular_price.$v_product->get_price_suffix() . '</del> <ins>' .
                       $prod_price . $v_product->get_price_suffix() . '</ins>';
}
return $prod_price;
}

After configuring the code snippet, the price of the variable products will be displayed as in the below screenshot.

Single price for variatble product


Explore our blog section for more related articles.

You can also check out WooCommerce and WordPress plugins in ELEX.

Next Hide Checkout Fields Based on the Shipping Method: WooCommerce (With Video)

    Leave a Reply

    WordPress Image Lightbox Plugin