Check cart for multiple items

Solved
Highlighted
Tourist
3 0 0

Hi,
I am looking for a solution to the following problem:
In the cart I ask for a specific product ID. If this is available, a text should be displayed. This also works. But if I add a second condition (and), the code does not work anymore. Neither if one of the products nor both are in the shopping cart, the text is displayed.

What am I doing wrong?

  {% for item in cart.items %}
                     {% if item.product.id == 4433457807456 and item.product.id == 4433484120160 %}
<p>Text to be displayed when both product id's are in the cart</p>
        {% endif %}      
  {% endfor %}

 

0 Likes
Highlighted
Shopify Expert
498 9 96

By using 'and', you're asking if a product id is BOTH of those numbers, which it cannot be. You would need to use 'or' instead.

1 Like
Highlighted
Tourist
3 0 0

Hey @gina-gregory , thanks for your prompt help. 

I see what you mean...But "or" doesn't solve my problem, right?

I want to check if two specific items are in the cart in order to show the correct message which belongs to only this combination of products (e.g. bike model 1 + mudguards). 

Thanks a lot,

Andy

0 Likes
Highlighted
Shopify Expert
498 9 96

This is an accepted solution.

Got it. Ok, so here's what you can do:

{% assign hasProductA = false %}
{% assign hasProductB = false %}
{% for item in cart.items %}
  {% if item.product.id == 4433457807456 %}
    {% assign hasProductA = true %}
  {% elsif item.product.id == 4433484120160 %}
    {% assign hasProductB = true %}
  {% endif %}      
{% endfor %}
{% if hasProductA and hasProductB %}
<p>Text to be displayed when both product id's are in the cart</p>
{% endif %}
1 Like
Highlighted
Tourist
3 0 0

@gina-gregory , you are amazing! 

Works perfectly and I can now adapt this code to whatever I need. Thank you so much for those basics! 

0 Likes