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

WooCommerce缺货商品价格显示代码修正:添加Year属性展示

修正WooCommerce缺货商品价格显示中的年份不生效问题

问题原因分析

原代码存在几个关键问题导致年份无法正常显示:

  • 重复声明global $product,覆盖了函数传入的$product参数,可能导致产品对象调用异常
  • WooCommerce自定义属性的slug默认是小写格式,原代码中pa_Year的大写Y不符合规范,无法匹配实际属性
  • 未对年份值做容错判断,若属性为空会直接显示空白
  • 冗余的$year赋值语句无意义,干扰后续逻辑

修正后的代码

add_filter( 'woocommerce_get_price_html', 'modify_price_out_of_stock_items', 9999, 2 );

function modify_price_out_of_stock_items( $price, $product ) {
    // 后台环境直接返回原价格
    if ( is_admin() ) return $price;

    // 仅处理缺货状态的商品
    if ( ! $product->is_in_stock() ) {
        // 获取自定义属性Year的值(注意slug为小写pa_year,若你的属性slug是大写则对应修改)
        $year = $product->get_attribute('pa_year');
        
        // 年份存在时才重新格式化价格
        if ( ! empty( $year ) ) {
            $price = sprintf( 'Last ticketed at %s in %s', $price, $year );
        }
    }

    return $price;
}

关键修改说明

  1. 移除多余的global $product,直接使用函数传入的产品对象,避免对象覆盖问题
  2. 使用小写属性slugpa_year,匹配WooCommerce自动生成属性的规则(若你手动设置了大写slug,可自行调整)
  3. 用$product->get_attribute()直接获取属性显示值,比wc_get_product_terms更简洁直接
  4. 添加非空判断,避免年份为空时出现异常显示
  5. 使用sprintf格式化字符串,代码可读性更强

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 07:18:34