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

Shopify产品页Related Products改按Tag而非Collection展示需求

当然可以!把关联商品从按collection匹配改成按相同tag匹配完全可行,下面我会给你具体的修改方案,你可以直接适配到你的related-products.liquid文件中:

核心修改思路

我们需要先拿到当前产品的所有标签,然后遍历店铺内的产品,筛选出带有相同标签且不是当前产品的商品,最后控制展示数量并渲染出来。

具体代码示例

替换你原来获取collection关联产品的代码,改成以下逻辑:

{% comment %} 第一步:获取当前产品的所有标签 {% endcomment %}
{% assign current_tags = product.tags %}

{% comment %} 第二步:初始化空数组存储匹配的关联产品 {% endcomment %}
{% assign matched_products = '' | split: '' %}

{% comment %} 第三步:遍历所有产品,筛选符合条件的商品 {% endcomment %}
{% for item in all_products %}
  {% comment %} 排除当前产品本身 {% endcomment %}
  {% if item.handle != product.handle %}
    {% comment %} 检查当前产品的标签是否和遍历的产品有重叠 {% endcomment %}
    {% for tag in item.tags %}
      {% if current_tags contains tag %}
        {% comment %} 避免重复添加同一个产品(如果多个标签匹配) {% endcomment %}
        {% unless matched_products contains item %}
          {% assign matched_products = matched_products | push: item %}
        {% endunless %}
        {% break %} {% comment %} 只要有一个标签匹配就停止检查该产品的其他标签,提升效率 {% endcomment %}
      {% endif %}
    {% endfor %}
  {% endif %}
{% endfor %}

{% comment %} 第四步:控制展示数量,比如最多显示4个 {% endcomment %}
{% assign related_products = matched_products | slice: 0, 4 %}

{% comment %} 第五步:渲染关联产品(保留你原来的HTML结构和样式即可) {% endcomment %}
{% if related_products.size > 0 %}
  <div class="related-products-section">
    <h2 class="section-title">相关商品</h2>
    <div class="products-grid">
      {% for product in related_products %}
        <article class="product-card">
          <a href="{{ product.url }}" class="product-link">
            <img 
              src="{{ product.featured_image | img_url: '300x300' }}" 
              alt="{{ product.title | escape }}"
              class="product-image"
            >
            <h3 class="product-title">{{ product.title }}</h3>
            <div class="product-price">
              {{ product.price | money }}
            </div>
          </a>
        </article>
      {% endfor %}
    </div>
  </div>
{% endif %}
关键注意点
  • 如果你原来的代码中是从特定collection获取产品(比如{% assign related_products = collection.products | where: 'id', '!=', product.id %}),直接把这部分替换成上面的标签筛选逻辑就行
  • all_products对象在Shopify中默认最多能获取20个产品,如果你的店铺产品超过20个,推荐用Shopify的search语法优化(比如{% assign search_query = 'tag:' | append: current_tags | join: ' OR tag:' %},再用{% assign matched_products = search.results %}),不过对于中小店铺来说,上面的遍历逻辑完全够用
  • 可以修改slice: 0, 4中的数字来调整展示的关联商品数量
  • 记得保留你原来模板中的样式类名,这样不会破坏页面的原有布局

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:14:12