WooCommerce Percentage Sale Badge
Replaces the default WooCommerce sale flash with a dynamic percentage-off badge calculated from the regular and sale price.
Module2 parts · by SnipCraft
PHPLogic
php
<?php
if ( ! class_exists( 'WooCommerce' ) ) { return; }
add_filter( 'woocommerce_sale_flash', 'scseed_percent_badge', 10, 3 );
function scseed_percent_badge( $text, $post, $product ) {
if ( $product->is_type( 'variable' ) ) {
$percentages = array();
$prices = $product->get_variation_prices();
if ( ! empty( $prices['regular_price'] ) ) {
foreach ( $prices['regular_price'] as $id => $regular ) {
$sale = isset( $prices['sale_price'][ $id ] ) ? (float) $prices['sale_price'][ $id ] : 0;
if ( $sale && (float) $regular > 0 ) {
$percentages[] = round( ( ( (float) $regular - $sale ) / (float) $regular ) * 100 );
}
}
}
if ( empty( $percentages ) ) { return $text; }
$pct = max( $percentages );
} else {
$regular = (float) $product->get_regular_price();
$sale = (float) $product->get_sale_price();
if ( ! $regular ) { return $text; }
$pct = round( ( ( $regular - $sale ) / $regular ) * 100 );
}
return '<span class="scseed-sale-badge">-' . absint( $pct ) . '%</span>';
}CSSStyles
css
.scseed-sale-badge {
display: inline-block;
background: #e74c3c;
color: #fff;
font-size: 0.75rem;
font-weight: 700;
padding: 3px 8px;
border-radius: 3px;
letter-spacing: 0.02em;
text-transform: uppercase;
line-height: 1.5;
}
.woocommerce ul.products li.product .scseed-sale-badge {
position: absolute;
top: 0.5rem;
right: 0.5rem;
z-index: 2;
}#frontend#woocommerce#product#badge#sales