7

I'm trying to list my categories (and sub categories, just one sub level) as a nav, and have the number of entries in each of those categories beside each one.

There is another question on here which achieves a simple list here but trying to apply that logic to what i have for my nav is scrambling my brain as everything I've tried throws an error.

This is what i have, taken from the Get Help section of the craft site:

<ul>
{% nav category in craft.categories.group('articleCategories') %}
    <li>
        <a href="{{ category.url }}">{{ category.title }}</a>
        {% ifchildren %}
            <ul>
                {% children %}
            </ul>
        {% endifchildren %}
    </li>
{% endnav %}
</ul>

Any thoughts on how i can get the number of entries each category has in it, in this?

12

Within your nav loop, you would use the method count() with an craft.entries Element Query, to only count the entries that are related to the category you're looping. Pass the category object to the relatedTo parameter.

{% nav category in craft.categories.group('articleCategories') %}

    {# Get the count of entries related to `category` #}
    {% set entryCount = craft.entries.relatedTo(category).count() %}

    {{ entryCount }}

{% endnav %}
2
  • Thank you carlcs! You are like a machine :^) Much appreciated!
    – Dan Owen
    Jan 29 '15 at 20:28
  • Is there a way to avoid the n+1 query in this situation?
    – aaandre
    Feb 18 at 8:16
3

Bonus Answer. If you want to sort by the amount of posts each category has you can do the following

{% set allCats = craft.categories.group('articleCategories').level(1).find() %}

{% set catArray = {} %}

{% for cat in allCats %}

    {% set catArray = catArray | merge({(cat.slug):craft.entries.relatedTo(cat).total() }) %}

{% endfor %}

{% set catArray = catArray|sort|reverse %}

{% for catSlug, count in catArray %}

    {% set category = craft.categories.slug(catSlug).first() %}

    <li class="categories__item"><a href="{{ category.url }}">{{ category.title }}</a></li>

{% endfor %}
1
  • 1
    Nice! Could well come in handy :)
    – Dan Owen
    Jan 31 '15 at 15:14

This site is temporarily in read only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .