Show the Discount Percentage on Sale Badges
Replaces the "Sale!" badge with the actual discount, for example "-25%". Variable products show the largest discount among their variations.
Opens WPIDE on
Code
add_filter( 'woocommerce_sale_flash', function ( $html, $post, $product ) {
if ( ! $product instanceof WC_Product ) {
return $html;
}
$percent = 0;
if ( $product->is_type( 'variable' ) ) {
foreach ( $product->get_children() as $child_id ) {
$child = wc_get_product( $child_id );
if ( ! $child || ! $child->is_on_sale() ) {
continue;
}
$regular = (float) $child->get_regular_price();
$sale = (float) $child->get_sale_price();
if ( $regular > 0 ) {
$percent = max( $percent, ( $regular - $sale ) / $regular * 100 );
}
}
} else {
$regular = (float) $product->get_regular_price();
$sale = (float) $product->get_sale_price();
if ( $regular > 0 && '' !== $product->get_sale_price() ) {
$percent = ( $regular - $sale ) / $regular * 100;
}
}
if ( $percent < 1 ) {
return $html;
}
return '<span class="onsale">-' . esc_html( (string) (int) round( $percent ) ) . '%</span>';
}, 10, 3 );
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.