-
Stefanie
Hi there,
in the old GP support forum I found this code to show the subcategories of a main category.
https://generatepress.com/forums/topic/list-subcategories/#post-679474It 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( array( 'id' => '', ), $atts, 'list_subcats' ); ob_start(); $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(); } );
-
Stefanie
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.