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

如何在Twig模板的Tease Product中获取WooCommerce产品标签并添加类

解决WooCommerce产品标签判断并添加样式类的问题

正确的Twig模板写法

你之前的判断逻辑有误,应该直接通过Timber产品对象的terms()方法获取该产品的所有产品标签(WooCommerce产品标签的taxonomy是product_tag,不是默认的post_tag),然后检查是否存在slug为bf24的标签:

{% for item in products %}
     {% set link = item.link %}
     {% set img_src = item.thumbnail.src('shop_single') %}

     {% if (grid_type == 'categories') %}
        {% set img_src = Image(item.meta('thumbnail_id')) %}
        {% if img_src == '' %}
          {% set img_src = placeholderImg %}
        {% endif %}
        {% set link = item.link %}
     {% endif %}

     {# 判断产品是否有BF24标签 #}
     {% set tagclass = '' %}
     {% for tag in item.terms('product_tag') %}
         {% if tag.slug == 'bf24' %}
             {% set tagclass = 'bf24' %}
             {% break %} {# 找到后跳出循环,提升效率 #}
         {% endif %}
     {% endfor %}

     {# 注意这里把{{tags}}改成{{ tagclass }} #}
     <div class="item flex justify-center {{ tagclass }} ">
        <a href="{{ link }}">
          <div class="overflow-hidden rounded-full w-[240px] h-[190px] bg-slate-100"><img class="w-full h-full object-cover" src="{{ img_src }}" alt=""></div>
             
          <div class="title text-2xl py-2 rounded-full px-2 {{ titles_bg }} max-w-[240px] text-center font-medium">{{ item.title }}</div>
            {# {% do action( 'woocommerce_after_shop_loop_item_title' )  %} #}
            {% do action( 'woocommerce_before_add_to_cart_form' ) %}
            {% if hide_titles == false %}
            {% endif %}
          </a>
        </div>
{% endfor %}

为什么之前的方法无效

  1. 你用的taxonomy.findTaxonomy({'tag':'BF24'})是获取整个tag分类下的所有内容,不是判断当前产品是否属于该标签,逻辑完全错误。
  2. WooCommerce的产品标签使用独立的taxonomyproduct_tag,不是WordPress默认的post_tag,所以不能直接用tag来调用。

PHP端无需额外处理

你之前的PHP代码$posts = Timber::get_posts(); $context['products'] = $posts;完全没问题,因为Timber的Timber\Post对象(WooCommerce产品继承该类)已经内置了terms()方法,可以直接在Twig中调用获取对应分类/标签,不需要额外传递标签数据到模板。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 01:57:13