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

在WooCommerce商品归档页显示折扣百分比遇NaN% Off问题求助

解决WooCommerce折扣百分比显示NaN% Off的问题

出现NaN(非数字)错误,核心原因是数值计算异常,比如正则价为空/0、价格未转成数值类型,或者$product对象未正确获取。以下是修复方案:

问题排查点

  • $regular_price可能为空字符串、0,导致除法运算时出现除以0的情况
  • get_regular_price()和get_sale_price()返回的是字符串,直接参与运算会引发类型错误
  • 部分场景下global $product未正确初始化,导致无法获取价格数据

修复后的代码

替换原有函数为以下版本,增加了类型校验、数值转换和异常防护:

// 计算并显示商品折扣百分比
function display_sale_percentage() {
    // 确保获取到有效商品对象
    global $product;
    if ( ! $product ) {
        $product = wc_get_product( get_the_ID() );
    }

    if ( $product && $product->is_on_sale() ) {
        // 获取价格并转换为数值类型
        $regular_price = (float) $product->get_regular_price();
        $sale_price = (float) $product->get_sale_price();

        // 防护正则价为0的情况,避免除以0
        if ( $regular_price <= 0 ) {
            return;
        }

        // 计算折扣百分比
        $discount_percentage = round( ( ($regular_price - $sale_price) / $regular_price ) * 100 );

        // 输出折扣标签
        echo '<span class="sale-percentage">' . $discount_percentage . '% off</span>';
    }
}

// 挂载到商品循环标题前的钩子
add_action( 'woocommerce_before_shop_loop_item_title', 'display_sale_percentage', 25 );

关键修复说明

  • 增加$product对象的兜底获取:当global $product失效时,通过wc_get_product(get_the_ID())重新获取商品对象
  • 强制转换价格为浮点型:避免字符串参与数学运算导致的异常
  • 增加正则价大于0的判断:彻底避免除以0引发的NaN错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 15:02:01