WordPress : Displaying categories and subcategories “tree like”

Suppose you want to show a category / subcategory “tree like” list on a WordPress page that gets the posts from a certain “main” category.
The following code, probably will be useful.

//# 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><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 style="padding-left:12px">';
echo '<a href="">'.$subcategory->cat_name.'</a></span>';
}
endif;
}

<pre>

Displaying categories and subcategories “tree like” list on WordPress


</pre>

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.