Show Parent category and Subcategory in WordPress

I need to show sub category in below to the respective parent category in wordpress Sidebar.

Without using plugin I need to show the parent category and sits sub categories in sidebar with following manner

Category1

     --Sub1

     --Sub2

Category2

   --Cat2Sub1

   --Cat2Sub2

Related posts

1 comment

  1. Please try with this code

    <?php
    if(is_category()) {
    
        $breakpoint = 0;
        $thiscat = get_term( get_query_var('cat') , 'category' );
        $subcategories = get_terms( 'category' , 'parent='.get_query_var('cat') );
    
        if(empty($subcategories) && $thiscat->parent != 0) {
            $subcategories = get_terms( 'category' , 'parent='.$thiscat->parent.'' );
        }
    
        $items='';
        if(!empty($subcategories)) {
            foreach($subcategories as $subcat) {
                if($thiscat->term_id == $subcat->term_id) $current = ' current-cat'; else $current = '';
                $items .= '
                <li class="cat-item cat-item-'.$subcat->term_id.$current.'">
                    <a href="'.get_category_link( $subcat->term_id ).'" title="'.$subcat->description.'">'.$subcat->name.' ('.$subcat->count.' posts)</a>
                </li>';
            }
            echo "<ul>$items</ul>";
        }
        unset($subcategories,$subcat,$thiscat,$items);
    }
    ?>
    

Comments are closed.