<p>You'd typically use the <a href="https://craftcms.com/docs/3.x/dev/filters.html#group" rel="nofollow noreferrer">group</a> filter for this. Depending on what you need to output, be sure to also use <a href="https://craftcms.com/docs/3.x/dev/eager-loading-elements.html" rel="nofollow noreferrer">eager loading</a> to improve performance.</p>
<pre><code>{% set groupedEntries = craft.entries.with(['yourOutputCatFieldHandle']).relatedTo(category).all()|group('yourOutputCatFieldHandle[0].title') %}

{% for cat, entries in groupedEntries %}
    &lt;h3&gt;{{ cat }}&lt;/h3&gt;
    &lt;ul&gt;
        {% for entry in entries %}
            &lt;li&gt;&lt;a href=&quot;{{ entry.url }}&quot;&gt;{{ entry.title }}&lt;/a&gt;&lt;/li&gt;
        {% endfor %}
    &lt;/ul&gt;
{% endfor %}
</code></pre>
<p>EDIT: alternative answer below to allow for using the correct category ordering as per the control panel's Structure order.</p>
<p>Note: this approach requires the <a href="https://github.com/TopShelfCraft/SuperSort" rel="nofollow noreferrer">supersort</a> plugin.</p>
<pre><code>{# ======================================
First, fetch entries related to this category,
then group the array by each category's
`lft` structure position, then sort the array
by those keys with supersort's ksort function
========================================= #}

{% set groupedEntries = craft.entries.with([
        'yourOutputCatFieldHandle'
    ])
    .relatedTo(category)
    .all()|group('yourOutputCatFieldHandle[0].lft')|supersort('ksort')
%}

{# ======================================
Next, create a hash map of those categories so we can
match up the `lft` left structure position
with the category's title later.
(google &quot;Nested Sets&quot; if you're really bored)
========================================= #}

{% if groupedEntries|length %}
    {% set catTitlesMap = craft.categories.group('yourOutputCatGROUPHandle').all()|group('lft') %}
{% endif %}

{# ======================================
Finally, loop through the grouped array,
matching up the accessory's `lft` position
with the hash map to get the right title...
========================================= #}

{% for cat, entries in groupedEntries %}
    &lt;h3&gt;{{ catTitlesMap[cat][0].title }}&lt;/h3&gt;
    &lt;ul&gt;
        {% for entry in entries %}
            &lt;li&gt;&lt;a href=&quot;{{ entry.url }}&quot;&gt;{{ entry.title }}&lt;/a&gt;&lt;/li&gt;
        {% endfor %}
    &lt;/ul&gt;
{% endfor %}
</code></pre>

CC BY-SA 4.0
2020-08-20T09:45:22.780Z
Hi James, thanks for looking at this.  Your code is almost working.  Initially I get an error "Impossible to access an attribute ("title") on a string variable ("5kW")" where '5kW' is the title of one of the categories and probably the first the loop encounters.  If I remove {{ cat.title }} it does indeed output the entries grouped by their category - but without the Category title ('cos I removed it).  Also, it seems to output the categories in date order when I need them in the actual order they appear in the CP.  4kW, 6kW, 8kW  ..etc.  So, how to get the {{ cat.title }} and orderBy working?
Martin
CC BY-SA 4.0
2020-08-20T10:19:20.567Z
Sorry that was a typo, corrected now... it should just be `{{ cat }}` as it's just a simple string (we already called `.title` in the grouping filter). For outputting in the CP-based order of the categories, that's a bit more complicated as our initial call is for the entries, not the categories... I'll have a think about it. Maybe something is possible with custom parameters: https://craftcms.com/docs/3.x/dev/eager-loading-elements.html#defining-custom-parameters-on-eager-loaded-elements
James Smith
CC BY-SA 4.0
2020-08-20T10:38:44.020Z
Brilliant, thanks James that worked!  Now to get the categories output in the right order :)
Martin
CC BY-SA 4.0
2020-08-20T10:47:17.543Z
I've updated the answer with a potential alternative approach to get the order correct.
James Smith
CC BY-SA 4.0
2020-08-20T11:05:27.887Z
Sorted! (literally).  This is great James thank you so much for your time.
Martin
CC BY-SA 4.0
2020-08-19T19:20:10.397Z
2020-08-20T10:46:50.770Z
2020-08-20T10:46:50.770Z
James Smith
<p>I have a Structure called &quot;Stoves&quot;.
Each Entry has two Category fields 'fuelType' and 'output'.</p>
<ul>
<li>Fuel Type categories = ''Wood Burning','Multi-Fuel','Gas' and 'Electric'.</li>
<li>Output categories = '4kW','6kW','8kW','10kW',</li>
</ul>
<p>On the category page template the following simple code gives me the correct entries based on the 'fuelType' field...  e.g. when viewing the 'Wood burning' page it shows me Wood Burning stoves.</p>
<pre><code>{% set entries = craft.entries.relatedTo(category).all() %}

{% for entry in entries %}
    &lt;a href=&quot;{{ entry.url }}&quot;&gt;{{ entry.title }}&lt;/a&gt;&lt;br&gt;
{% endfor %}
</code></pre>
<p>But I now need to <strong>also</strong> loop through the 'output' category group so I get something like the following:</p>
<p><strong>ALL Wood Burning Stoves</strong></p>
<p>Intro Text</p>
<p>start loop</p>
<ul>
<li><p><strong>4kW Stoves</strong></p>
</li>
<li><p>Stove_4kW_No.1</p>
</li>
<li><p>Stove_4kW_No.2</p>
</li>
<li><p>Stove_4kW_No.3</p>
</li>
<li><p><strong>6kW Stoves</strong></p>
</li>
<li><p>Stove_6kW_No.1</p>
</li>
<li><p>Stove_6kW_No.2</p>
</li>
<li><p><strong>8kW Stoves</strong></p>
</li>
<li><p>Stove_8kW_No.1</p>
</li>
<li><p>Stove_8kW_No.2</p>
</li>
<li><p>Stove_8kW_No.3</p>
</li>
<li><p>Stove_8kW_No.4</p>
</li>
</ul>
<p>...and so on....</p>
<p>end loop</p>
<p>Is this even possible?  Alternatively could I pull with individual entry queries using the individual 'output' category slugs?</p>
<p>Many thanks</p>

<categories><category><relatedto>
Display related entries on a category page filtered by another category field
# Display related entries on a category page filtered by another category field

(Asked by: username_0 on 2020-08-19)

I have a Structure called "Stoves".
Each Entry has two Category fields 'fuelType' and 'output'.

Fuel Type categories = ''Wood Burning','Multi-Fuel','Gas' and 'Electric'.
Output categories = '4kW','6kW','8kW','10kW',

On the category page template the following simple code gives me the correct entries based on the 'fuelType' field...  e.g. when viewing the 'Wood burning' page it shows me Wood Burning stoves.
{% set entries = craft.entries.relatedTo(category).all() %}

{% for entry in entries %}
    {{ entry.title }}
{% endfor %}

But I now need to also loop through the 'output' category group so I get something like the following:
ALL Wood Burning Stoves
Intro Text
start loop

4kW Stoves

Stove_4kW_No.1

Stove_4kW_No.2

Stove_4kW_No.3

6kW Stoves

Stove_6kW_No.1

Stove_6kW_No.2

8kW Stoves

Stove_8kW_No.1

Stove_8kW_No.2

Stove_8kW_No.3

Stove_8kW_No.4


...and so on....
end loop
Is this even possible?  Alternatively could I pull with individual entry queries using the individual 'output' category slugs?
Many thanks

**Tags:** categories, category, relatedto

---

## 1 answers

### Answer by username_1 on 2020-08-19. Score: 1 | Accepted answer

You'd typically use the group filter for this. Depending on what you need to output, be sure to also use eager loading to improve performance.
{% set groupedEntries = craft.entries.with(['yourOutputCatFieldHandle']).relatedTo(category).all()|group('yourOutputCatFieldHandle[0].title') %}

{% for cat, entries in groupedEntries %}
    {{ cat }}
    
        {% for entry in entries %}
            {{ entry.title }}
        {% endfor %}
    
{% endfor %}

EDIT: alternative answer below to allow for using the correct category ordering as per the control panel's Structure order.
Note: this approach requires the supersort plugin.
{# ======================================
First, fetch entries related to this category,
then group the array by each category's
`lft` structure position, then sort the array
by those keys with supersort's ksort function
========================================= #}

{% set groupedEntries = craft.entries.with([
        'yourOutputCatFieldHandle'
    ])
    .relatedTo(category)
    .all()|group('yourOutputCatFieldHandle[0].lft')|supersort('ksort')
%}

{# ======================================
Next, create a hash map of those categories so we can
match up the `lft` left structure position
with the category's title later.
(google "Nested Sets" if you're really bored)
========================================= #}

{% if groupedEntries|length %}
    {% set catTitlesMap = craft.categories.group('yourOutputCatGROUPHandle').all()|group('lft') %}
{% endif %}

{# ======================================
Finally, loop through the grouped array,
matching up the accessory's `lft` position
with the hash map to get the right title...
========================================= #}

{% for cat, entries in groupedEntries %}
    {{ catTitlesMap[cat][0].title }}
    
        {% for entry in entries %}
            {{ entry.title }}
        {% endfor %}
    
{% endfor %}

> **Comments:**
> **username_0**: Hi James, thanks for looking at this.  Your code is almost working.  Initially I get an error "Impossible to access an attribute ("title") on a string variable ("5kW")" where '5kW' is the title of one of the categories and probably the first the loop encounters.  If I remove {{ cat.title }} it does indeed output the entries grouped by their category - but without the Category title ('cos I removed it).  Also, it seems to output the categories in date order when I need them in the actual order they appear in the CP.  4kW, 6kW, 8kW  ..etc.  So, how to get the {{ cat.title }} and orderBy working?  
> **username_1**: Sorry that was a typo, corrected now... it should just be `{{ cat }}` as it's just a simple string (we already called `.title` in the grouping filter). For outputting in the CP-based order of the categories, that's a bit more complicated as our initial call is for the entries, not the categories... I'll have a think about it. Maybe something is possible with custom parameters: https://craftcms.com/docs/3.x/dev/eager-loading-elements.html#defining-custom-parameters-on-eager-loaded-elements  
> **username_0**: Brilliant, thanks James that worked!  Now to get the categories output in the right order :)  
> **username_1**: I've updated the answer with a potential alternative approach to get the order correct.  
> **username_0**: Sorted! (literally).  This is great James thank you so much for your time.  

---

