I have a entry field populated by categories. The number of categories an entry can have is unlimited and the categories are set up as nested categories i.e.
- first level
- ---second level
------third level
first level 2
- ---second level 2
- ------third level 2
I want to be able to list out any categories selected at the third level that the entry may have selected if a certain parent category is identified. So far I have the following code. This works but lists all child categories for the identified parent instead of just the selected ones.
What am I missing?
{% set cats = entry.categories %}
{% for cat in cats %}
{% if cat.slug == 'secondlevel1' or cat.slug == 'secondlevel2' %}
{% set catChildren = cats.descendantOf(cat.id).descendantDist('1') %}
{% if catChildren | length %}
{% for childCat in catChildren %}
{% set image = childCat.buildingBlockIcon.first() %}
{% if image %}
<img alt="{{ childCat.title }}" src="{{ image.url }}" />
{% endif %}
{% endfor %}
{% endif %}
{% endif %}
{% endfor %}
----- EDIT Solution -----
I worked this out
by changing one line of code line 4 above from
{% set catChildren = cat.level(2).children %}
to
{% set catChildren = cats.descendantOf(cat.id).descendantDist('1') %}
Now works a treat. Any better solutions feel free to post.