1

I am looking to output the child categories of a parent category. I only need to show the categories which have entries related to them.

I have done this to show all categories using

{% set entryIds = craft.entries.section('stories').ids() %}
{% set categories = craft.categories.relatedTo({ sourceElement: entryIds }).groupId(2).orderBy('title').all() %}

What is the best way to do this for subcategories.

1
  • What is wrong with using the same query format to get the subcategories? Commented Sep 11, 2019 at 16:47

1 Answer 1

1

Use the descendantOf parameter to select just the subcategories, then run an entries query to check if that category has any entries assigned to it.

<ul>
    {# loop through the subcategories #}
    {% for subCategory in craft.categories({
        groupId: 2,
        descendantOf: parentCategoryObject,
        orderBy: 'title'
    }).all %}
        {# check if this subcategory has at least one entry assigned to it #}
        {% set subCatEntries = craft.entries({
            section: 'blog',
            relatedTo: subCategory,
            limit: 1
        }) %}

        {# display a link to the subcategory page if entries are assigned to it #}
        {% if subCatEntries|length %}
            <li><a href="{{ subCategory.url }}">{{ subCategory.title }}</a></li>
        {% endif %}
    {% endfor %}
</ul>

You'll need to provide the parentCategoryObject yourself based on however your templating works.

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.