Shopify/Liquid中从元字段获取产品并循环展示的问题
解决Shopify元字段关联产品列表渲染问题
你的元字段返回的是产品GID(全局ID)字符串数组,而非直接的产品对象,所以原代码无法正确渲染产品卡片。以下是修正方案:
修正后的Liquid代码
<section class="product-list"> <div> {% for product_gid in product.metafields.custom.bundle %} {% assign bundle_product = all_products[product_gid] %} {% if bundle_product %} {% include 'single-product-card', product: bundle_product %} {% endif %} {% endfor %} </div> </section>
关键说明
- 通过GID获取产品对象:使用Shopify全局对象
all_products,传入产品GID即可获取对应的产品实例 - 添加有效性判断:
{% if bundle_product %}可以避免因无效GID导致的页面错误 - 匹配Snippet参数:如果你的
single-product-card代码片段接收的参数名不是product,而是原代码中的bundle_product,请将传参改为bundle_product: bundle_product
你选择的Product (List)元字段类型是符合需求的,出现GID数组的情况属于Shopify在部分场景下的返回格式,上述方法可完美兼容。
内容的提问来源于stack exchange,提问作者Cedric Hadjian
相关产品推荐
相关产品推荐

