更新 -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+版本。



