8

I need to get entries which are only in current category, not child categories.

So if I have a category structured like this:

Food
----Fruit
-------Apples
-------Bananas

I've got a categories template and I'm on the page for the Fruit category I want to know whether there's any entries just in the Fruit category and not all the entries in the Apples and Bananas categories.

Current I'm doing this

 craft.entries.relatedTo(category)

But I'm getting all the entries from the children categories as well, how do I get only the entries related to this specific category not child categories?

1 Answer 1

8

Since Apples and Bananas are children of Fruit, all entires that are related to Apples or Bananas are also related to Fruit, which is why you are getting the the results you are getting. If you need to exclude entries related to the subcategories, you can do something like this:

{% set dontInclude = [] %}

{% for child in craft.categories.descendantOf(category) %}
    {% set dontInclude = dontInclude|merge(craft.entries.relatedTo(child).ids) %}
{% endfor %}

{% set str = dontInclude|join(', not ') %}

{% set fruitEntries =  craft.entries({
    relatedTo: category,
    id: 'and, not '~str
}) %}

The above code will loop through Fruit's categories (Apple, Banana) and retrieve all the related entires and merging them into one array. Using the expanded craft.entries, you can exclude the entries related to Apple or Banana using the id: 'and, not' code. Hope this helps!

1
  • Awesome, that worked! Do you know if craft 3 will make this any easier? Aug 18, 2015 at 10:49

Your Answer

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

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