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

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

<pre><code>{% 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 %}
</code></pre>

CC BY-SA 4.0
2018-07-04T00:49:13.167Z
2018-07-04T00:49:13.167Z
Brad Bell
<p>**How can I modify this to orderBy the # of entries and then limit to the top 3? **   </p>

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

    &lt;a href="{{ categoryName.url }}"&gt;{{ categoryName.title }} &lt;sup&gt;({{numofEntries}})&lt;/sup&gt; &lt;/a&gt;
{% endfor %}
</code></pre>

<templating>
How can count and then order by the # of entries assigned to a category; and then limit to only the top 3?
# How can count and then order by the # of entries assigned to a category; and then limit to only the top 3?

(Asked by: username_0 on 2018-07-03)

**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() %}

    {{ categoryName.title }} ({{numofEntries}}) 
{% endfor %}

**Tags:** templating


---

## 1 answers

### Answer by username_1 on 2018-07-04. Score: 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 %}


---

