List products with tags matching article tags

Inside my blog articles, I want to display the products with tags that match the current article’s tags, limiting the results to only those tags beginning with “ngpc”.

Conditions:

  • An article contains the tags “ngpc_dsmb” , “ngpc_hgbv” , and “ngpc_rtcv”
  • Product 1 contains the tag “ngpc_dsmb”
  • Product 2 contains the tag “ngpc_hgbv”
  • Product 3 contains the tag “ngpc_rtcv”

Intended Result:

The article displays Product 1, Product 2, and Product 3

Actual Result:

The article displays Product 1

My current code:

{% for tag in article.tags %}
  {% if tag contains 'ngpc_' %}
    {% for product in collections.all.products %}
      {% if product.tags contains tag %}
        {{ product.title }},
      {% endif %}
    {% endfor %}
  {% endif %}
{% endfor %}

This works, but the output is limited to one product. Please assist? :slight_smile:

  {% if tag contains 'ngpc_dsmb' or 'ngpc_hgbv' or  'ngpc_dsmb' %}

sorry i misread I think this might work otherwise just check the tags again?? that they are exact

Thanks, but that doesn’t work. Any other suggestions?

That would be an ad hoc solution. Not every article will have the same tags, so I need to do this systematically.

What about something like this? I haven’t tested but I was just trying to work through the logic in my head:

{% assign article_tags = article.tags %}
    {% for product in collections.all.products %}
      {% if product.tags contains article_tags[forloop.index0] %}
        {{ product.title }},
      {% endif %}
    {% endfor %}

Thanks for the reply, but that actually doesn’t output anything. Got any other ideas?

I’ll try some other stuff, but a question I have is how many products does your store have? A for loop can only go through 50 iterations, so it’s possible that using collections.all.products it’s not even making it to any product with those tags. It might be more effective to make a collection with some of the products you would like to recommend based off a blog post and use that.

Also, I can see now my logic was completely off on that last suggestion, sorry if that wasted any of your time. Ill keep messing with it and see what I can come up with over the weekend.

I think you hit the nail on the head. Just now, I noticed that the output isn’t just one product every time. Actually, the number of products it displays seems random. Could this be because of the 50-iteration limit? The store has at least 80 products.

Confirmed, this was the cause. Each query is limited to 50 results. For this particular application, you can overcome this by querying each collection separately, provided your collections have fewer than 50 products.

This was helpful, thank you! Would you know how to have a fallback to show the full collection if none of the tags are present?