Are you a GenerateCustomer?

Do you have an active GP Premium or GenerateBlocks Pro license key?

Create a GenerateSupport account for GeneratePress and GenerateBlocks support in one dedicated place.

Create an account
Already have a GenerateSupport account? Login

Just browsing?

Feel free to browse the forums. Support for our free versions is provided on (GeneratePress, GenerateBlocks).

Want to become a premium user? Learn more below.

list subcategories

  • Hi there,

    in the old GP support forum I found this code to show the subcategories of a main category.

    It works very well, but there is a small problem: it also shows the categories that are empty (not assigned to a post). Is it possible to customize the code so that empty categories are not shown?

    Thank you!

  • Hi there,

    Give this code a try:

    add_shortcode( 'list_subcats', function( $atts ) {
        $atts = shortcode_atts(
                'id' => '',
        ), $atts, 'list_subcats' );
        $term_id = $atts['id'];
        $taxonomy_name = 'category';
        $term_children = get_term_children( $term_id, $taxonomy_name );
        echo '<ul class="list-subcats">';
        foreach ( $term_children as $child ) {
            $term = get_term_by( 'id', $child, $taxonomy_name );
            // Check if the term has any posts
            if ( $term->count > 0 ) {
                echo '<li><a href="' . get_term_link( $child, $taxonomy_name ) . '">' . $term->name . '</a></li>';
        echo '</ul>';
        return ob_get_clean();
    } );
  • Cool ๐Ÿ‘ ๐Ÿ™‚

    Thank you very much!

  • You are welcome ย  ๐Ÿ™‚

Viewing 4 posts - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.