加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 在WC 3.0的单个产品页面中显示销售价格附近的折扣百分比

发布时间:2020-12-13 18:09:32 所属栏目:PHP教程 来源:网络整理
导读:我在我的主题的function.php中有这个代码来显示价格后的百分比,它在WooCommerce v2.6.14中运行良好. 但是这个片段在WooCommerce 3.0版本上不再起作用了. 我该如何解决这个问题? 这是代码: // Add save percent next to sale item prices.add_filter( 'wooc
我在我的主题的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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读