
Display discount percentages on sale products on the shop page and single product page.
Discounts are a great way to increase sales and acquire more customers in your WooCommerce store. Offering discounts in your WooCommerce store on special day campaigns or regular sales, will increase your conversion and boost revenue.
WooCommerce has a default setting to show a “Sale” badge if the item is on sale. Now, what about showing the exact discount percentage, instead of just showing the sale badge? Let’s do it without using a plugin.
You can add the following snippets to your child theme’s functions.php file. It will display the percentage with the text ‘discount’ on your shop page and also on the single product page.
add_filter( 'woocommerce_sale_flash', 'bwc_add_percentage_to_sale_badge', 20, 3 );
function bwc_add_percentage_to_sale_badge( $html, $post, $product ) {
if( $product->is_type('variable')){
$percentages = array();
// Get all variation prices
$prices = $product->get_variation_prices();
// Loop through variation prices
foreach( $prices['price'] as $key => $price ){
// Only on sale variations
if( $prices['regular_price'][$key] !== $price ){
// Calculate and set in the array the percentage for each variation on sale
$percentages[] = round( 100 - ( floatval($prices['sale_price'][$key]) / floatval($prices['regular_price'][$key]) * 100 ) );
}
}
// We keep the highest value
$percentage = max($percentages) . '%';
} elseif( $product->is_type('grouped') ){
$percentages = array();
// Get all variation prices
$children_ids = $product->get_children();
// Loop through variation prices
foreach( $children_ids as $child_id ){
$child_product = wc_get_product($child_id);
$regular_price = (float) $child_product->get_regular_price();
$sale_price = (float) $child_product->get_sale_price();
if ( $sale_price != 0 || ! empty($sale_price) ) {
// Calculate and set in the array the percentage for each child on sale
$percentages[] = round(100 - ($sale_price / $regular_price * 100));
}
}
// We keep the highest value
$percentage = max($percentages) . '%';
} else {
$regular_price = (float) $product->get_regular_price();
$sale_price = (float) $product->get_sale_price();
if ( $sale_price != 0 || ! empty($sale_price) ) {
$percentage = round(100 - ($sale_price / $regular_price * 100)) . '%';
} else {
return $html;
}
}
return '<span class="onsale">' . $percentage . ' ' . esc_html__( 'Discount', 'woocommerce' ) . ' </span>';
}
And a bit of CSS to your child theme style.css file to decorate the text.
span.onsale {
color: #fff;
font-weight: 600;
background: #f75757;
border: #f75757;
}
The sale percentage also will show on the single product page.

