sale badge issue By Mikado Themes
Resolve the sale badge issue with Mikado Themes.
add_action('after_setup_theme', function () {
remove_all_filters('woocommerce_sale_flash');
add_filter('woocommerce_sale_flash', 'awdr_display_percentage_on_sale_badge', 30, 3);
});
if(!function_exists('awdr_display_percentage_on_sale_badge')){
function awdr_display_percentage_on_sale_badge($html, $post, $product)
{
$percentage = 0;
$discount_percentage = apply_filters('advanced_woo_discount_rules_get_product_discount_percentage', 0, $product);
if ($discount_percentage > 0) {
$percentage = $discount_percentage . '%';
} else {
if ($product->is_type('variable')) {
$percentages = array();
// This will get all the variation prices and loop throughout them
$prices = $product->get_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 - (floatval($prices['sale_price'][$key]) / floatval($prices['regular_price'][$key]) * 100));
}
}
// Displays maximum discount value
$percentage = max($percentages) . '%';
} elseif ($product->is_type('grouped')) {
$percentages = array();
// This will get all the variation prices and loop throughout them
$children_ids = $product->get_children();
foreach ($children_ids as $child_id) {
$child_product = wc_get_product($child_id);
$regular_price = (float)$child_product->get_regular_price();
$sale_price = (float)$child_product->get_sale_price();
if ($sale_price != 0 || !empty($sale_price)) {
// Calculate and set in the array the percentage for each child on sale
$percentages[] = round(100 - ($sale_price / $regular_price * 100));
}
}
// Displays maximum discount value
$percentage = max($percentages) . '%';
} else {
$regular_price = (float)$product->get_regular_price();
$sale_price = (float)$product->get_sale_price();
if ($sale_price != 0 || !empty($sale_price)) {
$percentage = round(100 - ($sale_price / $regular_price * 100)) . '%';
} else {
return $html;
}
}
}
if ($percentage > 0) {
$html = '<span class="onsale">' . esc_html__('-', 'woocommerce') . ' ' . $percentage . '</span>'; // If needed then change or remove "up to -" text
}
return $html;
}
}