如何从产品页面将第二个产品添加到Shopify中的购物车

时间:2020-05-04 18:36:31

标签: shopify shopify-api

我正在使用Shopify,并试图添加选项以在要购买的产品中添加礼品包装和手提箱。

我可以使用item.properties向用户询问选择,并将其显示在购物车中。

如果item.properties设置为“礼品包装”或“手提箱”,我现在想向购物车中添加其他产品。

此代码位于product-template.liquid中,但不起作用:

{% for property in item.properties %}
                {% if property.last == "Gift Wrap" %}
               <p>This would add gift wrap.</p>
            <script>
                jQuery.post('/cart/update.js', {
                updates: {
                32005672697928: 1
                }
                });
            </script>
              {% endif %}
              {% if property.last == "Carry Strap" %}
                <p>This would add carry strap.</p>
                {% endif %}
              {% endfor %}
            {% endunless %}

1 个答案:

答案 0 :(得分:0)

您的代码似乎不打算在产品页面上使用。看起来应该将其放在{% for item in cart.items %} ... {% endfor %}循环中的购物车页面上。

此外,即使客户添加2个以上包装的商品,此代码也只会添加1个包装产品。我将代码更改为如下所示:

{%- assign numWrappedItems = 0 -%}
{%- for item in cart.items -%}
  {%- for property in item.properties -%}
    {%- if property.last == "Gift Wrap" -%}
      {%- assign numWrappedItems = numWrappedItems | plus: item.quantity -%}
      {%- break -%}
    {%- endif -%}
  {%- endfor -%}

  ...
{%- endfor -%}

{%- if numWrappedItems > 0 -%}
<script>
jQuery.post('/cart/update.js', {
  updates: {
    32005672697928: {{ numWrappedItems }}
  }
});
</script>

我希望以上所述是合理的。