1

Having a bit of a brainfart here... If hotspotCategory is my entry's categoryfield and that category group has nested categories, how do I return only the top level categories?

{% set entryCats = entry.hotspotCategory %}
{% if entryCats | length %}
    <span class="filter_cat">
       {% for cat in entryCats %}
          {{ cat.title }} {% if not loop.last %}, {% endif %}
       {% endfor %}
     </span>
 {% endif %} 

this works but if I do something like

{% set entryCats = entry.hotspotCategory.level(1).all() %}

I get an

Impossible to invoke a method ("level") on an array.

error.

What am I missing here?

To clarify: my entry has the following categories attached (slow & fast food are subcategories):

- food & dining
--- slow food
--- fast food

Now, on the entry page I only want to display the top level category, not the subcategories.

0

3 Answers 3

1

You might want the siblings of the selected Category via siblingOf - I think you'll need to do this with two steps.

1

You have to get the first level and then you have to loop through them.

{% set query = craft.categories().group('YOUR_CATEGORY').level(1) %}

{# Execute the query and get the results #}
{% set entries = query.all() %}

{% for entry in entries %}
   {{ entry.title }}
{% endif %}

This will output only the first level of the category tree.

1

Turns out my issue was that I was lazy-loading hotspotCategory which returns an array, making .level(1) impossible. Once removed from the lazyloading everything worked as expected.

Your Answer

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

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