My code below creates a shortcode that will print the sale percentage of variable and simple products if its on sale.
My problem with this code is that with simple products only, the sale percentage is showing as 100% OFF when the product is not on sale. I.e. no sale price entered
If I set a sale price, so setting the product to be on sale, the percentage shown is correct.
The problem is isolated to simple products that are not on sale. The sale percentage should not be being displayed at all.
add_shortcode( 'sale-percentage', 'add_percentage_to_sale_badge' );
function add_percentage_to_sale_badge() {
global $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 - ( $prices['sale_price'][ $key ] / $prices['regular_price'][ $key ] * 100 ) );
}
}
$percentage = $percentages ? max( $percentages ) . '% Off' : '';
} else {
$regular_price = (float) $product->get_regular_price();
$sale_price = (float) $product->get_sale_price();
$percentage = round( 100 - ( $sale_price / $regular_price * 100 ) ) . '% Off SIMPLE';
}
$percentage = $percentage ? esc_html__( '', 'woocommerce' ) . ' ' . $percentage : '';
return $percentage;
}