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?


Within you nav loop, you would use the method total() with an craft.entries ElementCriteriaModel, to only count the entries that are related to the category you're looping. Pass the CategoryModel 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).total() %}

    {{ entryCount }}

{% endnav %}
| improve this answer | |
  • Thank you carlcs! You are like a machine :^) Much appreciated! – Dan Owen Jan 29 '15 at 20:28

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 %}
| improve this answer | |
  • 1
    Nice! Could well come in handy :) – Dan Owen Jan 31 '15 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.