phpwordpress

custom category tree in wordpress


Hi i want to create a tree of categories in wordpress like this :

<ul>
    <a href=""> PARENT1 </a>
    <li><a href=""> CHILD 1-1</a></li>
    <li><a href=""> CHILD 1-2</a></li>
     .
     .
     .
</ul>
<ul>
    <a href=""> PARENT2 </a>
    <li><a href=""> CHILD 2-1</a></li>
    <li><a href=""> CHILD 2-2</a></li>
     .
     .
     .
</ul>

i want something that creates categories list in above format and show only categories which have children and hide those who don't

I Tried Something like this but it didn't give me what i wanted

<?php $args = array(
'type'                     => 'post',
'child_of'                 => 0,
'parent'                   => '',
'orderby'                  => 'name',
'order'                    => 'ASC',
'hide_empty'               => 0,
'hierarchical'             => 1,
'exclude'                  => '',
'include'                  => '',
'number'                   => '',
'taxonomy'                 => 'category',
'pad_counts'               => false 
);
$cats = get_categories( $args );
foreach( $cats as $cat) {
    if($cat->parent == 0) {
        $head = $cat->name;
        $cat_id = $cat->term_id;
    }
    echo "<a href=''>" . $head . "</a>";
    wp_list_cats("sort_column=NAME&optioncount=0&hierarchical=1&hide_empty=0&child_of={$cat_id}");
}

?>


Solution

  • Thanks For Your Response , I Found the Solution : This Code Works Fine

         $args = array(
                'type'                     => 'post',
                'child_of'                 => 0,
                'parent'                   => 0,
                'orderby'                  => 'name',
                'order'                    => 'ASC',
                'hide_empty'               => 1,
                'hierarchical'             => 0,
                'exclude'                  => '',
                'include'                  => '',
                'number'                   => '',
                'taxonomy'                 => 'category',
                'pad_counts'               => false 
                );
                $cats = get_categories( $args );
                foreach( $cats as $cat) {
                    if($cat->parent == 0) {
                        $parent_cat = null;
                        $head = $cat->name;
                        $head_id = $cat->term_id;
                    }
                    echo "<ul><a class='parent-category' href=''>" . $head . "</a>";                                                    
                    wp_list_cats("sort_column=NAME&optioncount=0&hierarchical=1&hide_empty=0&child_of={$head_id}&show_option_none=");
                    echo "</ul>";
                }