Ad

Filter And Group Articles By Tags In Shopify?

- 1 answer

I'm trying to group blog articles in Shopify by tag in the main blog template. So far I have this, but when trying to compare the group_tag and article_tag it always returns false. The print out as the same thing on the front end, eg.

This articles tags: Hello World

FALSE Hello World != Hello World

{% for tag in blog.all_tags %}
    {% assign group_tag = tag %}

        <h2>{{ group_tag }}</h2>

        {% for article in blog.articles %}
            {% assign article_tag = article.tags %}

            <h3>{{ article.title }}</h3>
            <p>This articles tags: {{ article_tag }}</p>

              {% if 'group_tag' == 'article_tag' %}
                <p>TRUE {{ article_tag }} = {{ group_tag }}</p>
              {% else %}
                <p>FALSE {{ article_tag }} != {{ group_tag }}</p>
              {% endif %}

        {% endfor %}

{% endfor %}

Is there a better way to filter the articles or compare the values of tag (group_tag) and article.tags (article_tag)?

Ad

Answer

The reason they appear the same but the comparison returns false is group_tag is a string containing a single tag, whereas article_tag is an array of tags (that currently contains only one tag, "Hello World").

You also don't want quotation marks around the variable names. E.g. {% if 'group_tag' == 'article_tag' %} should be {% if group_tag == article_tag %}.

I would suggest using the contains operator instead:

{% for group_tag in blog.all_tags %}
  <h2>{{ group_tag }}</h2>

  {% for article in blog.articles %}
    {% if article.tags contains group_tag %}
      <h3>{{ article.title }}</h3>
      <p>This article's tags: {{ article.tags }}</p>
    {% endif %}
  {% endfor %}

{% endfor %}
Ad
source: stackoverflow.com
Ad