Loop through a collection using a collection ID

Hi there,

Trying to figure out how to loop through a collection using the collection ID. Is this possible? Right now I’m using the collection name, ie: collections['collection-name'].products but needing to transition away from that since the collection name can change over time.

I appreciate your support!

Thank you,

Andre

Have you tried doing the same loop but using the id instead of collections-name?

Hi @andrefox ,

The thing you’re putting in the square brackets in your example is actually the “handle” of the collection. (See https://shopify.dev/docs/api/liquid/basics#referencing-handles)

In the context of Shopify, collections have a few different properties that are relevant here, title, id, and handle:

title: The title of a collection is a human-readable string that can be changed over time. It is used to give a descriptive title to the collection, such as “Sale Potions” or “New Arrivals.”

id: The ID of a collection is a unique identifier assigned to it by Shopify. Unlike the collection title, the ID remains constant and does not change. Though it would not be ideal to hard-code ids in your theme because it harms readability of the code (they just look like a bunch of numbers).

handle: The handle of a collection is a machine-readable version of its title. It is a URL-friendly version that typically consists of lowercase letters, numbers, and hyphens. Handles are also unique and do not (but double check this) change, even if the collection title is updated.
It is possible to change the handle in some cases, eg, by changing it manually or as a result of migration or import.

So just keeping your code as it is should work if you change only the titles of collections later.

If you still really want to use IDs to loop over collections you could try something like this:

{% assign targetCollectionId = 'your-collection-id' %}
{% assign targetCollection = collections.all | where: 'id', targetCollectionId | first %}

{% for product in targetCollection.products %}
{{ product.title }}
{% endfor %}