I’m working on a Shopify theme, and I’m trying to implement a related products section based on the tags of the current article. The goal is to display products that share common tags with the article. However, the code I’ve implemented doesn’t seem to be working correctly. The related products section is not displaying as expected.
{% comment %} Display the related products section if there are any related products {% endcomment %}
{% if related_products_found == false %}
{# Display default set of products when no related products are found #}
{% for default_product in collections.all.products limit: limit %}
This will display the related products if the article and product has common tags and if there is no common tags it will display the default products with the limit.
@Anand0 I will not recommend this approach since I can see a performance issue with looping through all products, you can use Storefront API Search to fetch accurate data based on a list of tags, but anyway, this is the code on how to get the related products based on article tags in liquid.
Note: I have yet to test this in an actual store.
{% assign limit = 4 %}
{% assign counter = 0 %}
{% assign article_tags = article.tags | downcase %}
{% capture related_products_content %}{% endcapture %}
{% for related_product in collections.all.products %}
{% assign product_tags = related_product.tags | downcase %}
{% assign has_common_tag = false %}
{% for tags in article_tags %}
{% if product_tags contains tags %}
{% assign has_common_tag = true %}
{% comment %}
Stop the loop when detect at least 1 common tag
{% endcomment %}
{% break %}
{% endif %}
{% endfor %}
{% if has_common_tag %}
{% assign counter = counter | plus: 1 %}
{% capture related_products_content %}
{{ related_products_content }}
YOUR PRODUCT LIST CONTENT HERE!
{% endcapture %}
{% else %}
{% comment %}
Skip this loop since we dont have any common tags
{% endcomment %}
{% continue %}
{% endif %}
{% if counter == limit %}
{% comment %}
Stop the loop when we reach the maximum limit!
{% endcomment %}
{% break %}
{% endif %}
{% endfor %}
{% if counter %}
{% comment %}
Display captured related products
{% endcomment %}
{{ related_products_content }}
{% else %}
No related products found :(
{% endif %}