Site logo

Archived topic

short code edit - subcategory label

2 replies · Started by Jeffrey on December 30, 2020

Viewing posts 1–3 of 3

I have been using this code, now trying ot edit it to have a label that would disappear if there were no subcategories.

Any help for a php newbie?
What I added echo '<p>Available Subcategories</p>';
shows it, but no functionality of course.

add_shortcode( 'list_subcats', function() {
    ob_start();
    
	echo '<p>Available Subcategories</p>';
    $current_cat = get_queried_object();
    $term_id = $current_cat->term_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 );
	echo '<li><a href="' . get_term_link( $child, $taxonomy_name ) . '">' . $term->name . '</a></li>';
    }

    echo '</ul>';

    return ob_get_clean();
} );

Hi there,

try this:

add_shortcode( 'list_subcats', function() {
    ob_start();
    
    $current_cat = get_queried_object();
    $term_id = $current_cat->term_id;
    $taxonomy_name = 'category';
    $term_children = get_term_children( $term_id, $taxonomy_name );

    if (!empty($term_children)) {
        echo '<p>Available Subcategories</p>';
        echo '<ul class="list-subcats">';

        foreach ( $term_children as $child ) {
	    $term = get_term_by( 'id', $child, $taxonomy_name );
	    echo '<li><a href="' . get_term_link( $child, $taxonomy_name ) . '">' . $term->name . '</a></li>';
        }

    echo '</ul>';
    }
	
    return ob_get_clean();
} );

It should only output the title and the list if the $term_children is NOT empty.

perfect! thank you for the explanation!

This archived topic is closed to new replies.