Show the discount on sale badges
Sale badges show the discount, for example “-20%”, instead of “Sale!”. For variable products it’s the biggest discount.
<?php
add_filter(
'woocommerce_sale_flash',
static function ( $html, $post, $product ) {
if ( ! $product instanceof WC_Product ) {
return $html;
}
$percent = 0;
if ( $product->is_type( 'variable' ) ) {
$prices = $product->get_variation_prices( true );
foreach ( $prices['regular_price'] as $id => $regular ) {
$sale = (float) ( $prices['sale_price'][ $id ] ?? $regular );
if ( (float) $regular > 0 && $sale < (float) $regular ) {
$percent = max( $percent, (int) round( 100 * ( (float) $regular - $sale ) / (float) $regular ) );
}
}
} elseif ( '' !== $product->get_sale_price() && (float) $product->get_regular_price() > 0 ) {
$regular = (float) $product->get_regular_price();
$percent = (int) round( 100 * ( $regular - (float) $product->get_sale_price() ) / $regular );
}
return $percent > 0 ? '<span class="onsale">-' . $percent . '%</span>' : $html;
},
10,
3
);
Good to know
Applies to classic product templates and shop lists.
In these packs
- WooCommerce essentials: The small WooCommerce changes shop owners ask for most.