Показывать скидку в процентах от цены продажи на страницах с одним продуктом для WC 3.0+

У меня был этот код в function.php моей темы, чтобы отобразить процент после цены, и он работал нормально в WooCommerce v2.6.14.

Но этот фрагмент больше не работает на WooCommerce версии 3.0+.

Как я могу это исправить?

Вот этот код:

// Add save percent next to sale item prices.
add_filter( 'woocommerce_sale_price_html', 'woocommerce_custom_sales_price', 10, 2 );
function woocommerce_custom_sales_price( $price, $product ) {
$percentage = round( ( ( $product->regular_price - $product->sale_price ) / $product->regular_price ) * 100 );
return $price . sprintf( __(' Save %s', 'woocommerce' ), $percentage . '%' );
}

7

Решение

woocommerce_sale_price_html хук был заменен другим хуком в WooCommerce 3.0+, который теперь имеет 3 аргумента (но не $product аргумент больше).

Вот этот функциональный код:

// Only for WooCommerce version 3.0+
add_filter( 'woocommerce_format_sale_price', 'woocommerce_custom_sales_price', 10, 3 );
function woocommerce_custom_sales_price( $price, $regular_price, $sale_price ) {
$percentage = round( ( $regular_price - $sale_price ) / $regular_price * 100 ).'%';
$percentage_txt = __(' Save ', 'woocommerce' ).$percentage;
$price = '<del>' . ( is_numeric( $regular_price ) ? wc_price( $regular_price ) : $regular_price ) . '</del> <ins>' . ( is_numeric( $sale_price ) ? wc_price( $sale_price ) . $percentage_txt : $sale_price . $percentage_txt ) . '</ins>';
return $price;
}

Этот код находится в файле function.php вашей активной дочерней темы (или темы), а также в любом файле плагина.

Этот код протестирован и работает только для WooCommerce версии 3.0+


Обновление, чтобы избежать NAN% процентное значение когда обычные и продажные цены предварительно отформатированы в формате HTML:

add_filter( 'woocommerce_format_sale_price', 'woocommerce_custom_sales_price', 10, 3 );
function woocommerce_custom_sales_price( $price, $regular_price, $sale_price ) {
// Getting the clean numeric prices (without html and currency)
$regular_price = floatval( strip_tags($regular_price) );
$sale_price = floatval( strip_tags($sale_price) );

// Percentage calculation and text
$percentage = round( ( $regular_price - $sale_price ) / $regular_price * 100 ).'%';
$percentage_txt = __(' Save ', 'woocommerce' ).$percentage;

return '<del>' . wc_price( $regular_price ) . '</del> <ins>' . wc_price( $sale_price ) . $percentage_txt . '</ins>';
}

Этот код находится в файле function.php вашей активной дочерней темы (или темы), а также в любом файле плагина.

Этот код протестирован и работает только для WooCommerce версии 3.0+ (спасибо @AsifRao)

10

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

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

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