0

**How can I modify this to orderBy the # of entries and then limit to the top 3? **

{% for categoryName in craft.categories.group('markets') %}
    {% set numofEntries = craft.entries.section('posts').relatedTo(categoryName).total() %}

    <a href="{{ categoryName.url }}">{{ categoryName.title }} <sup>({{numofEntries}})</sup> </a>
{% endfor %}
1

Ideally you'd do this from a custom plugin so you could write some queries directly against the database.

If you're looking to do this from a template, this should work, albeit it's not very efficient.

{% set entryArr = {} %}

{# Store the slug as the key in an array and the total number as the value #}
{% for categoryName in craft.categories.group('markets') %}
    {% set entryArr = entryArr|merge({(categoryName.slug): craft.entries.section('posts').relatedTo(categoryName).total()}) %}
{% endfor %}

{# Sort the array by the descending value maintaining the keys #}
{% set entryArr = entryArr|sort|reverse %}

{# Grab the first 3 values from the array #}
{% set entryArr = entryArr|slice(0, 3) %}

{# print them off #}
{% for slug, number in entryArr %}
    {% set categoryName = craft.categories.slug(slug).one() %}
    {{ categoryName.title }} - ({{number}})
{% 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.