Solved

Is looping through a specific Shopify collection possible?

itsmesteveyp
Tourist
9 1 2

I would like to loop through a particular collection, returning the first product that matches a given tag (slides) and the first product that doesn't match. 

{% for product in collection.products %}
{% if product.tags contains 'Slides' %}
{% break %}
{% else %}
{{ product.url }}
{% break %}
{% endif %}
{% endfor %}
Accepted Solution (1)

Jason
Shopify Expert
11190 225 2282

This is an accepted solution.

Something like this. Depending on how large your collection is do be aware the loop might not touch all products. It will only look at the current paginated set, or at most 1000 products.

{% assign slidesProduct = false %}
{% assign generalProduct = false %}

{% for product in collection.products %}
  {% if slidesProduct and generalProduct %}{% break %}{% endif %}
  {% if product.tags contains 'Slides' and slidesProduct == false %}
    {% assign slidesProduct = product %}  
    {% continue %}
  {% elsif generalProduct == false %}
    {% assign generalProduct = product %}  
    {% continue %}
  {% endif %}
{% endfor %}

 

The above is not tested and smashed out on mobile so take it as inspiration only. You'll end up with two variables that are either false, or have product info inside. You should be able to take that and do something with that.

★ I jump on these forums in my free time to help and share some insights. Not looking to be hired, and not looking for work. http://freakdesign.com.au ★

View solution in original post

Replies 2 (2)

Jason
Shopify Expert
11190 225 2282

This is an accepted solution.

Something like this. Depending on how large your collection is do be aware the loop might not touch all products. It will only look at the current paginated set, or at most 1000 products.

{% assign slidesProduct = false %}
{% assign generalProduct = false %}

{% for product in collection.products %}
  {% if slidesProduct and generalProduct %}{% break %}{% endif %}
  {% if product.tags contains 'Slides' and slidesProduct == false %}
    {% assign slidesProduct = product %}  
    {% continue %}
  {% elsif generalProduct == false %}
    {% assign generalProduct = product %}  
    {% continue %}
  {% endif %}
{% endfor %}

 

The above is not tested and smashed out on mobile so take it as inspiration only. You'll end up with two variables that are either false, or have product info inside. You should be able to take that and do something with that.

★ I jump on these forums in my free time to help and share some insights. Not looking to be hired, and not looking for work. http://freakdesign.com.au ★
itsmesteveyp
Tourist
9 1 2

This is plenty to get me started. Thank you, Jason!