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

基于WooCommerce分类术语的自定义缺货预订消息失效问题

问题解答

1. 旧代码片段在WooCommerce 6.5+版本失效的原因

WooCommerce 6.4及后续版本,对woocommerce_availability_text钩子的参数规则、库存状态判断逻辑做了调整,旧代码依赖的参数传递、函数调用逻辑不再适配新版本,因此会失效。

2. 你的代码存在的问题

  • woocommerce_availability_text钩子仅支持2个参数($text和$product),你额外添加的$product_cat参数无法被钩子正确传递,会导致变量未定义报错。
  • 使用$product->tags作为has_term的分类法参数是错误的,产品标签的官方分类法名称是product_tag,产品分类则是product_cat。
  • has_term函数需要明确传入检查的产品对象,你遗漏了这个参数,导致无法正确判断当前产品是否匹配目标术语。
  • __()函数内直接嵌套HTML标签不是合理写法,会导致翻译逻辑和样式结构耦合,不利于后期维护。

3. 修正后的代码

function custom_get_availability_text( $text, $product ) {
    // 仅在产品管理库存、处于预售状态且库存为0时触发逻辑
    if ( $product->managing_stock() && $product->is_on_backorder() && $product->get_stock_quantity() === 0 ) {
        // 检查产品标签匹配情况
        if ( has_term( '2 à 5 werkdagen', 'product_tag', $product ) ) {
            $text = '<p><span style="color: #99cc00;"><strong>' . __( 'Geschatte levertijd: 2 à 5 werkdagen', 'your-theme-domain' ) . '</strong></span></p>';
        } elseif ( has_term( '1 à 2 weken', 'product_tag', $product ) ) {
            $text = '<p><span style="color: #99cc00;"><strong>' . __( 'Geschatte levertijd: 1 à 2 weken', 'your-theme-domain' ) . '</strong></span></p>';
        } elseif ( has_term( '2 à 3 weken', 'product_tag', $product ) ) {
            $text = '<p><span style="color: #99cc00;"><strong>' . __( 'Geschatte levertijd: 2 à 3 weken', 'your-theme-domain' ) . '</strong></span></p>';
        // 检查产品分类或标签是否为Abonnementen
        } elseif ( has_term( 'Abonnementen', 'product_cat', $product ) || has_term( 'Abonnementen', 'product_tag', $product ) ) {
            $text = '<p><strong>' . __( 'Doorlopende betalingsopdracht', 'your-theme-domain' ) . '</strong></p>';
        }
    }
    return $text;
}
add_filter( 'woocommerce_availability_text', 'custom_get_availability_text', 10, 2 );

修正说明

  • 移除无效的$product_cat参数,保持钩子回调参数与官方定义一致。
  • 明确指定has_term的分类法类型,并传入$product对象作为检查目标,确保匹配逻辑准确。
  • 将翻译文本与HTML结构分离,__()函数仅处理需翻译的内容,替换your-theme-domain为你的主题实际文本域。
  • 简化is_on_backorder()调用,使用默认参数即可满足需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 19:39:56