2

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%}
4

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 > 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.

  • Interesting! Yes, in my use case there could be two or more categories assigned at level 2 or 3. – mjr Apr 29 '15 at 13:23
  • I wonder if it would be possible to make an array and sort by level? – mjr Apr 29 '15 at 13:23
1

You could sort by level descending (which will order by deepest-to-shallowest), and then lft ascending (which will order by top-to-bottom, for entries at the same level).

{% set category = craft.categories()
    .group('myGroup')
    .orderBy('level DESC, lft ASC')
    .one() %}
  • great, thank you – mjr Jun 13 at 21:38
0

I think the best approach for the time being is the code sample in the question. Always open to explore new ideas in the future.

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.