Get Shopify products grouped by their collections

by Amir Sadeghian Posted on | Shopify

Shopify is an e-commerce platform that has been built using Ruby on Rails language. If you would like to customize your Shopify store your options are very limited. Shopify has a specific series of objects for every entity. For example, a collection is an object. Collections is another object that contains all collections. In this article, I will show you how to get each collection from your Shopify store. Then we try to get all the products in each collection.

Get all collections in collections object

A collection is an object contains all collections in the Shopify store. Using a for loop we can iterate through all collections and get them one by one. Following code snippet shows how to show the title of all collections in the store.

{% for collection in collections %}
	<div class="collection-title">{{ collection.title }}</div>
{% endfor %}

Get products in a collection object

Following snippet allows us to get the products in a collection using the collection-handle as the index of collections object. This example will show the title of products in “All” collection.

{% for product in collections['all'].products %}
	<div class="collection-product">
		{{ product.title }}
	</div>
{% endfor %}

If we would like to get products belongs to each collection group by collection we can combine the first code snippet with the second one. Following snippet shows this logic. In this snippet, we use the collection.handle as the index of collections array and then we get the products belongs to that collection.

{% for collection in collections %}
	<div class="collection row">
		<div class="collection-title">{{ collection.title }}</div>
		{% for product in collections[collection.handle].products %}
			<div class="collection-product">
{{ product.title }}
			</div>
		{% endfor %}
	</div>
{% endfor %}

If you are interested to learn more about Shopify theme customization please join my online Shopify course.