我在我的主题的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 . '%' );
}
woocommerce_sale_price_html钩子已经被WooCommerce 3.0中的一个不同的钩子所取代,它现在有3个参数(但不再是$product参数).
这是功能相似的代码:
// Only for WooCommerce version 3.0+
add_filter( 'woocommerce_format_sale_price',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版
Update to avoid
NAN%percentage value when regular and sale prices are html pre-formatted:
add_filter( 'woocommerce_format_sale_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)