Using Woocommerce, I have successively removed sale badges and prices from product archives pages with the following code:
// Remove Sales Flash
add_filter('woocommerce_sale_flash', 'woo_custom_hide_sales_flash');
function woo_custom_hide_sales_flash()
{
return false;
}
// Remove prices on archives pages
remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10 );
All the products are variable products and all variations have the same prices. Also actually all prices are sale prices.
I would like to add the discounted percentage after each variable price range, in single product pages. I have tried using the following code:
add_filter( 'woocommerce_sale_price_html', 'woocommerce_custom_sales_price', 10, 2 );
function woocommerce_custom_sales_price( $price, $product ) {
$percentage = round( ( ( $product->regular_price – $product->sale_price ) /
$product->regular_price ) * 100 );
return $price . sprintf( __(' Save %s', 'woocommerce' ), $percentage . '%' );
}
But I dont get anything
What I am doing wrong and how can this be done?
Any help on this will be appreciated.
I have been testing the code and as you are targeting the sale price range for variable products it's better to use a custom hooked function in woocommerce_format_sale_price
filter hook that is located in wc_format_sale_price()
function.
That will allow to display the saved discount percentage after the price range when all variations have the same prices. If variations prices are different, then this percentage will only appear on variations prices.
So I have revisited your code:
// Removing sale badge
add_filter('woocommerce_sale_flash', '__return_false');
// Removing archives prices
remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10 );
// Add the saved discounted percentage to variable products
add_filter('woocommerce_format_sale_price', 'add_sale_price_percentage', 20, 3 );
function add_sale_price_percentage( $price, $regular_price, $sale_price ){
// Strip html tags and currency (we keep only the float number)
$regular_price = strip_tags( $regular_price );
$regular_price = (float) preg_replace('/[^0-9.]+/', '', $regular_price);
$sale_price = strip_tags( $sale_price );
$sale_price = (float) preg_replace('/[^0-9.]+/', '', $sale_price);
// Percentage text and calculation
$percentage = __('Save', 'woocommerce') . ' ';
$percentage .= round( ( $regular_price - $sale_price ) / $regular_price * 100 );
// return on sale price range with "Save " and the discounted percentage
return $price . ' <span class="save-percent">' . $percentage . '%</span>';
}
Code goes in function.php file of your active child theme (active theme).
Tested and works.