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

仅为带特定标签的WooCommerce产品添加短代码失败,求解决

问题:WooCommerce仅为带VIP标签的产品在短描述后添加短代码

我原本有一段可以在所有产品短描述下方添加短代码的代码:

add_filter('woocommerce_short_description','ts_add_text_short_descr');
function ts_add_text_short_descr($description){
   $text = do_shortcode('[my-shortcode]');
  return $description . $text;
}

之后我想改成仅为带有“VIP”产品标签的产品添加该短代码,写了下面这段代码,但无法正常工作:

add_filter('woocommerce_short_description', 'ts_add_text_short_descr');
function ts_add_text_short_descr($description) {
    global $product;   

    // Check if the product has a "VIP" tag
    $product_tags = wp_get_post_terms($product->get_id(), 'product_tag');
    $has_vip_tag = false;
    foreach ($product_tags as $tag) {
        if ($tag->slug === 'vip') {
            $has_vip_tag = true;
            break;
        }
    }

    // If the product has the tag "VIP", add the shortcode
    if ($has_vip_tag) {
        $text = do_shortcode('[my-shortcode]');
        return $description . $text;
    } else {
        return $description;
    }
}

请问有其他可行的实现方法吗?


可行的替代实现方法

方法一:使用has_term简化判断(推荐)

直接用WordPress内置的has_term函数检查产品标签,代码更简洁,同时避免全局变量失效的问题:

add_filter('woocommerce_short_description', 'ts_add_text_short_descr');
function ts_add_text_short_descr($description) {
    $product_id = get_the_ID();
    
    // 检查产品是否包含slug为'vip'的产品标签
    if (has_term('vip', 'product_tag', $product_id)) {
        $text = do_shortcode('[my-shortcode]');
        return $description . $text;
    }
    
    return $description;
}

方法二:确保全局$product变量有效

如果依赖全局$product,先检查变量是否为有效对象,避免报错:

add_filter('woocommerce_short_description', 'ts_add_text_short_descr');
function ts_add_text_short_descr($description) {
    global $product;

    // 若全局$product无效,尝试通过当前ID获取产品对象
    if (!is_a($product, 'WC_Product')) {
        $product = wc_get_product(get_the_ID());
    }

    if ($product) {
        // 提取所有标签的slug,检查是否包含'vip'
        $tag_slugs = wp_list_pluck($product->get_tags(), 'slug');
        if (in_array('vip', $tag_slugs)) {
            $text = do_shortcode('[my-shortcode]');
            return $description . $text;
        }
    }

    return $description;
}

方法三:利用过滤器的第二个参数

woocommerce_short_description过滤器支持第二个参数$post,可以直接从这里获取产品信息,无需依赖全局变量:

add_filter('woocommerce_short_description', 'ts_add_text_short_descr', 10, 2);
function ts_add_text_short_descr($description, $post) {
    // 确认当前内容是产品,且带有vip标签
    if ($post->post_type === 'product' && has_term('vip', 'product_tag', $post->ID)) {
        $text = do_shortcode('[my-shortcode]');
        return $description . $text;
    }
    
    return $description;
}

内容的提问来源于stack exchange,提问作者thuận đinh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 22:17:38