Depending on the collection viewed we want to display a different image on the collection products. It is a common case, some products can be used in different ways or can have multiple variants. When seeing a collection it makes sense for the user to see the appropriate image. This improves the user experience and provides a better way of showcasing your products.
Demo
White chairs collection showing default featured product image
Black chairs collection showing matched variant product image
The Logic
- Match the collection by its handle. In that collection, we will show different product images.
- Find the custom variant/image based on an option name and option value.
- Modify the collection product item markup to use the matched variant.
The scenario
- We have 2 collections: white chairs and black chairs.
Both collections fully or partially contain the same products. - In the white chairs collection, we want to show the featured product image.
In the black chairs collection, we want to show the black product variant image. - Clicking on a product from the black collection should lead to the black variant.
Clicking on a product from the white collection should lead to the default variant. - Our products have both white and black variants and have images assigned.
Matching the collection
Find your collection Liquid code. Usually, you can find the collection code in templates/collection.liquid
or sections/collection-template.liquid
In the collection Liquid code, you need to identify the code that generates the product item. In most cases this is what you are looking for: {% render 'product-grid-item' %}
We want to match the black products collection, we can match it by its handle:
If the collection handle is "black-chairs" and we pass 2 variables:
custom_option_name: 'color'
and custom_option_value: 'black'
We will use these variables, later on, to find in product-grid-item
the first variant that has the option name "color" and the option value "black".
Finding the desired variant/image
If the collection handle is "black-chairs" we will look into the product options for the first variant that has the option name "color" and the option value "black".
If the match is found featured_image
and product_url
will have the values pulled from that matched variant instead of the default product. We need to modify product-grid-item
to use those new variables instead.
Replacing product-grid-item variables
The next part can be tricky, you need to replace the references of:
product.featured_image
to featured_image
product.url
to product_url
original code
becomes
Helper files
To better understand the code changes required, you can have a look at the modified files of Shopify Simple theme: sections/collection-template.liquid, snippets/product-grid-item.liquid