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

//# 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>';


2 thoughts on “WordPress : Displaying categories and subcategories “tree like””

Leave a Comment

Your email address will not be published.

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

%d bloggers like this: