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?

1
  • 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!? Sep 2, 2019 at 11:22

1 Answer 1

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 and acknowledge that you have read and understand our privacy policy and code of conduct.

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