1

I'm trying to show the other entries assigned to the same nested category (on an entry template) but get an error if I use .last() which I was hoping would show the nested category assigned entries (and not all assigned to all levels of the same category,

Any ideas?

{# set the category group #}
{% set categoryGroup = craft.categories.group('products') %}

{% set entries = craft.entries.relatedTo(categoryGroup)  %}  

{# only show entries assigned to the same nested category #}
{% for sameCat in entries.last()  %}  
    <p>{{ sameCat.title }}</p>
{% endfor %}

{# note: using .last throws error – Impossible to access an attribute ("title") on a string variable ("1").
 #}

2 Answers 2

1

Get the first category of the entry you're currently on :

{% set currentEntryCategory = entry.categoryHandle.one().id %}

This assumes you limited the category to only be assigned once to the entry, otherwise you'll have to loop through all assigned categories to find the nested one you want.

Use that category ID to get the other entries that are relatedTo it :

{% set entries = craft.entries.relatedTo(currentEntryCategory).all() %}
{% for relatedEntry in entries %}
    {{ relatedEntry.title }}
{% endfor %}

If you want to exclude the current entry that you're on from the query :

{% set entries = craft.entries.relatedTo(currentEntryCategory).id('not ' ~ entry.id).all() %}
0
1

Thanks for the code snippets, this now works (below) as I was using .last with craft 3 and not .inReverse().one(),

{% set currentEntryCategory = entry.productCategory.one() %}
{% set entry = craft.entries.relatedTo(currentEntryCategory).inReverse().one() %}

<p>{{ entry.title }}</p>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.