0
votes

I'm using Shopify and am trying to add the options to add gift wrap and a carry case to products being bought.

I can use the item.properties to ask the user for the choice and show that in the cart.

I now want to add an additional product to the cart if item.properties is set to "gift wrap" or "carry case".

This code is placed in the product-template.liquid but does not work:

{% 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

1 Answers

0
votes

Doesn't seem the code you have was intended to be used on the product page. It looks like it should be placed on the cart page within the {% for item in cart.items %} ... {% endfor %} loop.

Also, this code will add only 1 wrap product, even if customers add 2+ wrapped items. I would change the code to something like the below:

{%- 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>

I hope the above makes sense.