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

Shopify条件化库存数量显示问题:仅需展示库存<50的变体

解决Shopify变体库存显示不符合条件的问题

首先得明确你的核心需求:切换变体时,仅当当前选中变体的库存数量小于50时才显示库存提示,对吧?你的代码逻辑本身没问题,但出现所有变体都显示库存的情况,大概率是代码位置不对,或者缺少前端JS同步变体切换后的状态导致的。

问题根源拆解

  1. 服务器端渲染的局限性:Shopify的current_variant是服务器端渲染的,默认指向产品的第一个变体。如果只靠Liquid代码,切换变体时页面不会自动重新判断库存条件,可能让你误以为所有变体都触发了显示。
  2. 代码位置错误:要是你把这段代码放在了遍历所有变体的循环里,却始终用current_variant(默认变体)做判断,就会导致每个变体选项下都显示默认变体的库存,看起来像是“所有变体都显示了库存”。

针对性解决方案

方案1:随变体切换动态显示符合条件的库存

把代码放在展示当前变体信息的区域(比如加购按钮上方),再配合JS监听变体切换事件,实时更新库存提示:

{% comment %} 初始渲染默认变体的库存提示 {% endcomment %}
{% if current_variant.inventory_quantity < 50 %} 
  <h4 id="inventory-notification"> 
    <span id="inventoryQuantity">{{ current_variant.inventory_quantity }}</span> available. 
  </h4> 
{% else %}
  <h4 id="inventory-notification" style="display: none;"></h4>
{% endif %}

{% comment %} 监听变体切换,动态更新显示 {% endcomment %}
<script>
document.addEventListener('DOMContentLoaded', function() {
  const productForm = document.querySelector('form[action="/cart/add"]');
  if (!productForm) return;

  productForm.addEventListener('change', function() {
    const selectedVariant = Shopify.ProductForm.getCurrentVariant(productForm);
    const notificationEl = document.getElementById('inventory-notification');
    const quantitySpan = document.getElementById('inventoryQuantity');

    if (selectedVariant && selectedVariant.inventory_quantity < 50) {
      quantitySpan.textContent = selectedVariant.inventory_quantity;
      notificationEl.style.display = 'block';
    } else {
      notificationEl.style.display = 'none';
    }
  });
});
</script>

方案2:直接列出所有库存小于50的变体

如果你是想在页面上一次性展示所有符合条件的变体库存,可以遍历所有变体并添加条件判断:

<h3>Low Stock Variants:</h3>
{% for variant in product.variants %}
  {% if variant.inventory_quantity < 50 %}
    <p>{{ variant.title }}: <span>{{ variant.inventory_quantity }}</span> available.</p>
  {% endif %}
{% endfor %}

额外检查项

  • 确认变体的inventory_management设置为「Shopify」,否则inventory_quantity可能无法正确获取(第三方库存管理需用对应属性)。
  • 如果你的店铺有预留库存设置,建议用inventory_quantity_available代替inventory_quantity,获取真实可用库存数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:45:50