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””

    1. Bikram Shrestha – Nepal – I am Web Developer and the software engineer

      You can search for Beginner’s Guide for WordPress on google and start learning WordPress.

Leave a Comment

Your email address will not be published.

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

Exit mobile version