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:

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

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

2 Answers 2


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 %}
  • Thank you carlcs! You are like a machine :^) Much appreciated!
    – Dan Owen
    Jan 29, 2015 at 20:28
  • Is there a way to avoid the n+1 query in this situation?
    – aaandre
    Feb 18, 2021 at 8:16

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
    Nice! Could well come in handy :)
    – Dan Owen
    Jan 31, 2015 at 15:14

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.