Отображение процента скидки на значок продажи в Woocommerce 3

Это работает для простых продуктов, но дает мне две ошибки для переменных продуктов. При продаже флэш-архива я получаю NAN% с ошибкой «Обнаружено нечисловое значение».

Мой код:

add_filter( 'woocommerce_sale_flash', 'add_percentage_to_sale_bubble' );
function add_percentage_to_sale_bubble( $html ) {
global $product;
$percentage = round( ( ( $product->regular_price - $product->sale_price ) / $product->regular_price ) * 100 );
$output ='<span class="onsale">SALE<br>-'.$percentage.'%</span>';
return $output;
}

Любые идеи о том, как это исправить?

Любая помощь высоко ценится.

1

Решение

Код, который вы используете, устарел со времен Woocommerce 3. Вместо этого попробуйте следующее, которое также обрабатывает переменные продукты:

add_filter( 'woocommerce_sale_flash', 'add_percentage_to_sale_badge', 20, 3 );
function add_percentage_to_sale_badge( $html, $post, $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));
}
}
// We keep the highest value
$percentage = max($percentages) . '%';
} else {
$regular_price = (float) $product->get_regular_price();
$sale_price    = (float) $product->get_sale_price();

$percentage    = round(100 - ($sale_price / $regular_price * 100)) . '%';
}
return '<span class="onsale">' . esc_html__( 'SALE', 'woocommerce' ) . ' ' . $percentage . '</span>';
}

Код помещается в файл function.php активной дочерней темы (или активной темы). Проверено и работает.

0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector