Search code examples
wordpresscustom-post-type

show categories and subcategories hierarchically custom post


I use this code for get all categories and subcategories, this work but not show subcategories hierarchically.

$args = array(
                'hide_empty'    => 1,
                'hierarchical'  => 1,
                'pad_counts'    => false
            );

$categories = get_terms('project_category', $args); 
echo '<ul>';
            foreach ($categories as $category) {
                echo '<li class="s"></li><li><a href="#'. $category->slug .'" data-filter=".category-'. $category->slug .'">'. $category->name .'</a> B</li>';
            }
echo '</ul>';

I can't use wp_list_categories() because don´t show ul tag and adds some other div

as I can distinguish between categories and subcategories unused wp_list_categories()


Solution

  • Use this way for display categories and subcategories

    <?php
    
    $parent_cat_arg = array('hide_empty' => false, 'parent' => 0 );
    $parent_cat = get_terms('category',$parent_cat_arg);//category name
    
    foreach ($parent_cat as $catVal) {
    
        echo '<h2>'.$catVal->name.'</h2>'; //Parent Category
    
        $child_arg = array( 'hide_empty' => false, 'parent' => $catVal->term_id );
        $child_cat = get_terms( 'category', $child_arg );
    
        echo '<ul>';
            foreach( $child_cat as $child_term ) {
                echo '<li>'.$child_term->name . '</li>'; //Child Category
            }
        echo '</ul>';
    
    }
    ?>
    

    Output enter image description here