1

I have a number of entries that all belong under a Channel that I created. Each entry has a category field where the user can select one or many categories to associate the entry with.

I am displaying these entries on my page, but would like to display each entry under the appropriate category.

For example, my entries are currently displayed like this:

  • Entry 1 (Category A)
  • Entry 2 (Category C)
  • Entry 3 (Category A)
  • Entry 4 (Category B)
  • Entry 5 (Category A)

I want it to display like this:

  • Entry 1 (Category A)
  • Entry 3 (Category A)
  • Entry 5 (Category A)
  • Entry 4 (Category B)
  • Entry 2 (Category C)

What's the best way to do this?

1 Answer 1

2

This will exclude empty categories, meaning they don't have any entries associated with them.

{% set entryIds = craft.entries.section('channelHandle').ids() %}
{% set categories = craft.categories.relatedTo({ sourceElement: entryIds }).group('categoryGroupHandle') %}

{% for category in categories %}
    <h2>{{ category.title }}</h2>
    <ul>
        {% set entries = craft.entries.section('channelHandle').relatedTo(category) %}
        {% for entry in entries %}
            <li><a href="{{ entry.url }}">{{ entry.title }}</a></li>
        {% endfor %}
    </ul>
{% endfor %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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