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

Shopify关联商品板块如何排除已售罄商品?

解决Shopify关联商品板块隐藏售罄商品的问题

我懂你想解决的是Shopify店铺里关联商品板块不展示售罄商品的问题,之前直接在代码开头加{% if product.available %}没起作用对吧?这是因为那个位置的product指的是当前页面的主商品,不是关联商品列表里的每个商品,自然过滤不到目标内容~

正确的修改思路

你需要在遍历关联商品的循环内部,或者提前筛选出所有可用的关联商品,再进行渲染。结合你提供的代码片段,给你两种可行的修改方案:

方案1:在循环内直接判断

先找到你遍历关联商品的{% for %}循环(通常是获取到关联collection之后的循环),在输出商品内容前加上判断条件,过滤掉不可用的商品:

{% if collection and collection.all_products_count > 1 %} 
  {% assign col = collection.handle %} 
{% else %} 
  {% assign col = product.collections.last.handle %} 
{% endif %} 
{% for tag in product.tags %} 
  {% if tag contains 'meta-related-collection-' %} 
    {% assign related_col_handle = tag | remove: 'meta-related-collection-' %}
    {% assign col = related_col_handle %}
  {% endif %}
{% endfor %}

<!-- 先把handle转为collection对象 -->
{% assign related_collection = collections[col] %}

{% for related_product in related_collection.products %}
  <!-- 只渲染可用的关联商品 -->
  {% if related_product.available %}
    <div class="related-product">
      <a href="{{ related_product.url }}">
        <img src="{{ related_product.featured_image | img_url: 'small' }}" alt="{{ related_product.title }}">
        <h4>{{ related_product.title }}</h4>
        <span>{{ related_product.price | money }}</span>
      </a>
    </div>
  {% endif %}
{% endfor %}

方案2:提前筛选可用商品(更高效)

用Shopify的where过滤器先把关联collection里的可用商品筛选出来,再判断是否有内容需要渲染,避免无效循环:

{% if collection and collection.all_products_count > 1 %} 
  {% assign col = collection.handle %} 
{% else %} 
  {% assign col = product.collections.last.handle %} 
{% endif %} 
{% for tag in product.tags %} 
  {% if tag contains 'meta-related-collection-' %} 
    {% assign related_col_handle = tag | remove: 'meta-related-collection-' %}
    {% assign col = related_col_handle %}
  {% endif %}
{% endfor %}

{% assign related_collection = collections[col] %}
<!-- 提前筛选所有可用的关联商品 -->
{% assign available_related_products = related_collection.products | where: 'available', true %}

{% if available_related_products.size > 0 %}
  <div class="related-products-section">
    <h3>相关商品</h3>
    {% for related_product in available_related_products %}
      <div class="related-product-item">
        <a href="{{ related_product.url }}">
          <img src="{{ related_product.featured_image | img_url: 'medium' }}" alt="{{ related_product.title }}">
          <h4>{{ related_product.title }}</h4>
          <p>{{ related_product.price | money }}</p>
        </a>
      </div>
    {% endfor %}
  </div>
{% else %}
  <!-- 没有可用关联商品时的提示 -->
  <p>暂无相关在售商品</p>
{% endif %}

为什么之前的方法无效?

你之前在代码开头添加的{% if product.available %},判断的是当前页面展示的主商品是否在售,和关联商品列表里的每个商品没有关系,所以根本无法过滤掉售罄的关联商品。必须把判断条件放在关联商品的循环逻辑里,或者提前筛选目标商品才行。

内容的提问来源于stack exchange,提问作者Or Ben-Yossef

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:13:50