I have a category tree like this and I have an entry that has four categories A, A1, B, C2:

  • A
    • A1
    • A2
  • B
    • B1
    • B2
  • C
    • C1
    • C2

I want a query that ignores A and returns only A1, B, C2, because I don't want to display the parent category of a sub-category that's also displayed.

{% for category in entry.businessTypes.all() %}{{ category.title }}{% endfor %} returns all: A, A1, B, C2

{% for category in entry.businessTypes.leaves().all() %}{{ category.title }}{% endfor %} returns A2, C2 but not B.

{% for category in entry.businessTypes.hasDescendants().all() %}{{ category.title }}{% endfor %} returns A, B but not A1, C2.

Any suggestions are appreciated.


I could not test it, but you could try:

If you always have a Parent and 2 levels

entry.businessTypes.level('>= 2').all()

If you want to only get the lowest, you could try to assign it with a condition:

{% if categories = entry.businessTypes.children %} 
    {% set categories = entry.businessTypes.level('>= 2').all() %}
{% else categories = entry.businessTypes.children %} 
    {% set categories = entry.businessTypes.all() %}
{% endif %}

{% for category in categories %} ... {% endfor %}
| improve this answer | |

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.