You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WooCommerce分类页面显示商品折扣节省百分比

在WooCommerce中计算并显示促销商品的总节省百分比

嘿,我来帮你搞定这个问题!你遇到的sale_price和regular_price无法直接访问的情况,是因为WooCommerce的产品对象属性被标记为protected,这是框架的设计规范——它不鼓励直接操作内部属性,而是提供了官方的公共方法来获取这些值,这样能避免后续版本更新导致代码失效。

下面是具体的解决步骤和代码示例:

1. 获取产品对象

首先你需要拿到对应的WC_Product对象,根据场景不同有两种常见方式:

  • 在产品循环(比如商城列表页)中,直接调用全局对象:
    global $product;
    
  • 通过产品ID获取:
    $product_id = get_the_ID(); // 或者直接传入你的产品ID
    $product = wc_get_product( $product_id );
    

2. 检查产品是否处于促销状态

在计算之前,先判断产品是否正在促销,避免无效计算:

if ( $product->is_on_sale() ) {
    // 执行计算逻辑
}

3. 通过公共方法获取价格值

使用WooCommerce提供的公共方法来获取常规价格和促销价格,这些方法会自动处理数据格式和兼容性:

$regular_price = (float) $product->get_regular_price();
$sale_price = (float) $product->get_sale_price();

4. 计算节省百分比

这里要注意处理常规价格为0的情况,避免除以0的错误:

if ( $regular_price > 0 ) {
    $savings_amount = $regular_price - $sale_price;
    $savings_percent = round( ( $savings_amount / $regular_price ) * 100 );
} else {
    $savings_percent = 0; // 或者根据需求显示其他内容
}

5. 显示节省百分比

最后把计算结果输出到页面上,比如:

echo '<span class="savings-percent">节省 ' . $savings_percent . '%</span>';

完整示例代码

把以上步骤整合起来,放在你需要显示的位置(比如产品模板文件中):

global $product;

if ( $product && $product->is_on_sale() ) {
    $regular_price = (float) $product->get_regular_price();
    $sale_price = (float) $product->get_sale_price();

    if ( $regular_price > 0 ) {
        $savings_percent = round( ( ( $regular_price - $sale_price ) / $regular_price ) * 100 );
        echo '<div class="product-savings">✅ 立省 ' . $savings_percent . '%</div>';
    }
}

这样就能完美绕过protected属性的限制,而且代码是符合WooCommerce官方规范的,后续版本更新也不用担心失效~

内容的提问来源于stack exchange,提问作者snack_overflow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:58:44