List child categories which have entries based on the current categories 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.
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.

&lt;ul&gt;
    {# 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 %}
            &lt;li&gt;&lt;a href="{{ subCategory.url }}"&gt;{{ subCategory.title }}&lt;/a&gt;&lt;/li&gt;
        {% endif %}
    {% endfor %}
&lt;/ul&gt;


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