Hiển thị phần trăm sale trong WooCommerce

Gỡ bage slae

/**
 * @snippet       Remove SALE badge @ Product Archives and Single Product
 * @how-to        businessbloomer.com/woocommerce-customization
 * @author        Rodolfo Melogli, Business Bloomer
 * @compatible    WooCommerce 7
 * @community     https://businessbloomer.com/club/
 */
  
remove_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_show_product_loop_sale_flash', 10 );
remove_action( 'woocommerce_before_single_product_summary', 'woocommerce_show_product_sale_flash', 10 );
 
// ---------------
// IN ALTERNATIVE USE THIS ONLY
 
add_filter( 'woocommerce_sale_flash', '__return_null' );

Thay đổi

add_filter( 'woocommerce_sale_flash', 'bbloomer_rename_sale_badge', 9999 );
 
function bbloomer_rename_sale_badge() {
   return '<span class="onsale">ON OFFER</span>';
}
 
// NOTE: PLEASE KEEP THE <SPAN> TAG

// Hiển thị % sale
// Hook to display the sale percentage on both product pages and shop loop
add_action('woocommerce_before_shop_loop_item_title', 'ts_show_sale_percentage', 25);
add_action('woocommerce_before_single_product_summary', 'ts_show_sale_percentage', 25);

function ts_show_sale_percentage() {
global $product;
$max_percentage = 0; // Initialize $max_percentage here

if (!$product->is_on_sale()) return;

if ($product->is_type('simple')) {
$max_percentage = (($product->get_regular_price() - $product->get_sale_price()) / $product->get_regular_price()) * 100;
} elseif ($product->is_type('variable')) {
foreach ($product->get_children() as $child_id) {
$variation = wc_get_product($child_id);
$price = $variation->get_regular_price();
$sale = $variation->get_sale_price();
$percentage = 0; // Initialize $percentage here

if ($price != 0 && !empty($sale)) {
$percentage = ($price - $sale) / $price * 100;
}

if ($percentage > $max_percentage) {
$max_percentage = $percentage;
}
}
}

if ($product->is_type('grouped')) {
return; // Skip grouped products
}

if ($max_percentage > 0) echo "<div class='sale-perc'>-" . round($max_percentage) . "%</div>";
}