我在我主题的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 . '%' );
}
更新 -2019 (避免舍入价格问题( - 2017 (避免
NAN%
百分比值(
woocommerce_sale_price_html
钩被WooCommerce 3.0 中的另一个挂钩替换,现在有3个参数(但没有 $product
参数(。
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)
$_reg_price = floatval( strip_tags($regular_price) );
$_sale_price = floatval( strip_tags($sale_price) );
// Percentage calculation and text
$percentage = round( ( $_reg_price - $_sale_price ) / $_reg_price * 100 ).'%';
$percentage_txt = ' ' . __(' Save ', 'woocommerce' ) . $percentage;
$formatted_regular_price = is_numeric( $regular_price ) ? wc_price( $regular_price ) : $regular_price;
$formatted_sale_price = is_numeric( $sale_price ) ? wc_price( $sale_price ) : $sale_price;
echo '<del>' . $formatted_regular_price . '</del> <ins>' . $formatted_sale_price . $percentage_txt . '</ins>';
}
此代码在您的活动子主题(或主题(或任何插件文件中的function.php文件中。
测试了代码并有效。对于WooCommerce版本3.0 (感谢@mikebcn和@asifrao(
用于舍入百分比,您可以使用round()
,number_format()
或number_format_i18n()
:
$percentage = number_format_i18n( ( $_reg_price - $_sale_price ) / $_reg_price * 100, 0 ).'%';
$percentage = number_format( ( $_reg_price - $_sale_price ) / $_reg_price * 100, 0 ).'%';
原始答案代码:这是功能相似的代码:
// 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 。