1

The following is using commerce product entries, but I'm reasonably sure it could be any entry.

With the following category taxonomy:

- Category 1
    - Category 1A
- Category 2
- Category 3
...

If I have a product entry "Product 1" with a category field selected to "Category 1A", when looping though all categories to return products for that category, how can I list the entry ONLY for "Category 1A" and not it's any of its ancestors e.g. "Category 1"?

Currently, I'm using the following:

{% nav category in productCategories %}
    <li>
        {{ category.title }}
        {% set products = craft.products().relatedTo(category).all() %}
        {% for product in products %}
            {{ product.title }}
        {% endfor %}
        {% ifchildren %}
            <ul>
                {% children %}
            </ul>
        {% endifchildren %}
    </li>
{% endnav %}

Which returns

- Category 1
    Product 1
    - Category 1A
        Product 1
- Category 2
- Category 3
...

But what I want is for it to only be visible on the selected category.

- Category 1
    - Category 1A
        Product 1
- Category 2
- Category 3
...

Is there a way to do this using categories? or am I best using a structure?

  • Using a structure seems to work however I would like to retain the ability of getting all entries for a parent category, best of both worlds!? – Matt Jenkins Sep 2 at 11:22
1

Instead of using nav, you can just use your own code for getting children. I.e. loop through level 1, then within that loop check if they have ancestors at level 2, then within that loop check if they have ancestors for level 3 etc.

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.