2

Entries can have one of two categories and one tag. (People = entries | program = categories | year = tag)

On the pages I'd like to display entries related to the category and grouped by tag. However, I don't want the tag to display if there are no entries with that tag and in that category.

The following code works, but it displays empty tags that I'd like hidden.

{% set entryIds = craft.entries.section('fellows').ids() %}
{% set tags = craft.tags.relatedTo({ sourceElement: entryIds }).groupId(2).find() | reverse %}
   {% for tag in tags %}
      <h3>{{ tag.slug }} {{ category.title }}</h3>
          {% for entry in craft.entries({
                            relatedTo: [
                              'and',
                              { targetElement: category },
                              { targetElement: tag },
                              ],
                              limit: (null),
                              }) %}
           {% include '_entryblock.twig' %} 
           {% endfor %} 
    {% endfor %} 

This currently displays the following — but I don't want it to display 2018 in Program A or 2017 in Program B since neither of those have entries.

Program A:

/program-a (category)
  |__2018 (tag)
  |__2017
       |__Bono (entry)
       |__The Edge
  |__2016
       |__Ringo
       |__Paul  

Program B:

/program-b
  |__2018
       |__Chris Martin
       |__Jonny Buckland
  |__2017
  |__2016
       |__Florence
       |__The Machine  
1

Here's a good tutorial on how to achieve this: https://straightupcraft.com/articles/how-do-i-only-display-a-list-of-categories-that-have-entries-and-hide-empty-categories

1

you can use .count() to determine if there is an empty tag:

{% for tag in tags %}
{% set count = craft.entries.section('fellows').relatedTo(category).relatedTo(tag).count() %}
  {% if count > 0 %}
     <h3>{{ tag.slug }} {{ category.title }}</h3>
         {% for entry in craft.entries({
                                relatedTo: [
                                  'and',
                                  { targetElement: category },
                                  { targetElement: tag },
                                  ],
                                  limit: (null),
                                  }) %}
               {% include '_entryblock.twig' %} 
  {% endif %}
{% endfor %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.