Restyle Sale Badge With Percentage Off
Replaces the generic WooCommerce 'Sale!' badge with a calculated percentage-off label (e.g. '-25%') for simple products; variable products keep the original badge.
PHPby SnipCraft
php
<?php
if ( ! class_exists( 'WooCommerce' ) ) {
return;
}
/**
* To hide the sale badge entirely instead of restyling it, replace the
* filter below with:
* add_filter( 'woocommerce_sale_flash', '__return_false' );
*/
add_filter( 'woocommerce_sale_flash', 'scseed_percentage_sale_badge', 10, 3 );
function scseed_percentage_sale_badge( $html, $post, $product ) {
if ( $product->is_type( 'variable' ) ) {
return $html; // keep default for variable products
}
$regular = (float) $product->get_regular_price();
$sale = (float) $product->get_sale_price();
if ( $regular > 0 && $sale >= 0 && $sale < $regular ) {
$pct = round( ( ( $regular - $sale ) / $regular ) * 100 );
return '<span class="onsale">-' . esc_html( $pct ) . '%</span>';
}
return $html;
}#badge#display#products#sale#woocommerce