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

WooCommerce特定分类商品缺货提示语自定义问题

WooCommerce特定分类商品缺货提示语自定义方案

我已经通过以下代码成功修改了全局的商品缺货/有货提示语:

function custom_stock_messages( $text, $product ) {
    if ( $product->get_stock_quantity() <= 0 ) {
        // 全局缺货提示
        $custom_message = '通常2-5个工作日内发货';
    } else {
        // 全局有货提示
        $custom_message = '现货秒发';
    }
    return $custom_message;
}
add_filter( 'woocommerce_get_availability_text', 'custom_stock_messages', 10, 2 );

但尝试给特定分类的缺货商品设置专属提示语时,下面的代码无法生效:

function custom_out_of_stock_message( $html, $product ) {
    // 目标分类别名
    $target_category = 'your-category-slug';

    // 检查商品是否属于目标分类
    if ( has_term( $target_category, 'product_cat', $product->get_id() ) ) {
        // 自定义缺货提示HTML
        $html = '<p class="stock out-of-stock">Custom Out of Stock Message</p>';
    }

    return $html;
}
add_filter( 'woocommerce_get_availability_text', 'custom_out_of_stock_message', 10, 2 );

问题原因

  1. woocommerce_get_availability_text过滤器的返回值是纯文本,不是HTML结构,直接返回HTML会破坏原有渲染逻辑
  2. 没有判断商品是否处于缺货状态,只要属于目标分类就替换内容,逻辑错误
  3. 两个同优先级的钩子函数会互相覆盖,导致后注册的函数可能不生效

正确解决方案

将全局提示和特定分类提示的逻辑整合到同一个函数中,按「分类判断→库存状态判断」的顺序处理:

function custom_stock_messages( $text, $product ) {
    // 定义目标分类的别名(替换成你的分类slug)
    $target_category = 'your-category-slug';
    // 目标分类的专属缺货提示
    $target_out_of_stock_msg = '该分类商品缺货,预计7-10个工作日发货';
    
    // 先判断商品是否属于目标分类,再结合库存状态返回对应提示
    if ( has_term( $target_category, 'product_cat', $product->get_id() ) ) {
        if ( $product->get_stock_quantity() <= 0 ) {
            return $target_out_of_stock_msg;
        } else {
            // 目标分类有货时的提示,可自定义
            return '该分类商品现货秒发';
        }
    } else {
        // 非目标分类商品,使用全局提示
        if ( $product->get_stock_quantity() <= 0 ) {
            return '通常2-5个工作日内发货';
        } else {
            return '现货秒发';
        }
    }
}
add_filter( 'woocommerce_get_availability_text', 'custom_stock_messages', 10, 2 );

关键说明

  • 只保留一个钩子函数,避免优先级冲突
  • 使用has_term()准确判断商品所属分类,参数依次为「分类slug」「分类 taxonomy(product_cat是WooCommerce商品分类的默认taxonomy)」「商品ID」
  • 严格区分「分类归属」和「库存状态」的判断顺序,确保逻辑准确
  • 返回纯文本即可,WooCommerce会自动套用默认的HTML结构和样式

内容的提问来源于stack exchange,提问作者Τ Μακρίδης

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 20:05:14