Displaying categories and subcategories “tree like” list on WordPress

Suppose you want to show a category / subcategory “tree like” list on a WordPress page that gets the posts from a certain “main” category.
Suponha que você quer mostrar uma “árvore” de categorias / subcategorias numa página WordPress que contém posts de uma certa categoria “principal”.

The following code, probably will be useful.
O código a seguir, provavelmente lhe será útil.

//# first of all, you need to get the category array,
//   and I did it, putting the line bellow inside the loop
$category = get_the_category(get_the_ID());

// once you have the category array, the rest of the code will work wherever you want on the page 

//# getting the main category of the page
$catid=$category[0]->category_parent;
if($catid==0){
  $catid=$category[0]->cat_ID;
}

//# now letz get the children categories of the main category
$categories = get_categories('child_of='.intval($catid)); 					 

foreach ($categories as $category) {
    //# check if it is a real parent category with subcategories
    if ($category->parent ==$catid):
        echo '<span class="category"><a href="">'.$category->cat_name.'</a></span>';
        //# here we go, getting the subcategories
        $subcategories=  get_categories('child_of='.intval($category->cat_ID));
        foreach ($subcategories as $subcategory) {
            echo '<span class="subcategory" style="padding-left:12px">';
            echo '<a href="">'.$subcategory->cat_name.'</a></span>';
        }
    endif;
}
Share on TwitterSave on DeliciousShare via email