Getting the first category of the deepest level for an entry I want to get the first category of the deepest level for an entry.

For example if the category structure looks like this

Ocean Life > Fish > Gold Fish

I want "Gold Fish"

Here is what I've come up with so far. Is there a more elegant solution that I'm missing?

            {% set primaryCategory = entry.categories.level(3).first %}
            {% if primaryCategory is empty %}
                {% set primaryCategory = entry.categories.level(2).first %}
            {% endif%}
            {% if primaryCategory is empty %}
                {% set primaryCategory = entry.categories.level(1).first %}
            {% endif%}
Assuming you are only assigning one category (and thus by default all of that categories ancestors), then getting the 'last' returned category should work.

{% set category = entry.categories.last() %}


Otherwise, you will need some logic of some kind. What you have works, or perhaps something where you don't need to know how many levels there are.

{% set level = 0 %}
{% for category in entry.categories %}
    {% set level = category.level &gt; level ? category.level : level %}
{% endfor %}
{% set category = entry.categories.level(level).first %}


However, this will still not retrieve all the categories if there is more than one category set with same level.