[Resolved] short code edit – subcategory label

Home Forums Support [Resolved] short code edit – subcategory label

Home Forums Support short code edit – subcategory label

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #1599737
    Jeffrey

    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();
    } );
    
    #1599768
    David
    Staff
    Customer Support

    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.

    #1599785
    Jeffrey

    perfect! thank you for the explanation!

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