Display All Categories and Subcategories in WordPress

Display All Categories and Subcategories in Wordpress

How to Display All Categories and Subcategories in WordPress

WordPress comes with the ability to sort your Content or Products into Categories, Tags and Taxonomies. One of the major difference between Categories and Tags is that Categories can have Subcategories or child categories. In this article, we will show you how to display Categories and Subcategories in WordPress.

Just paste the below code inside the WordPress

$args = array(
‘orderby’ => ‘name’,
‘parent’ => 0,
‘hide_empty’ => FALSE );

$categories = get_categories( $args );
$first = true;
foreach ($categories as $category) {

$theid = $category->term_id;
$my_table = $wpdb->prefix.”term_taxonomy”;
$children = $wpdb->get_results( “SELECT term_id FROM $my_table WHERE parent=$theid” );
$no_children = count($children);
// echo count($children);
if ($no_children >= 1) {
echo ‘<h2 id=”classRight”>’.$category->cat_name.'</h2>’;
// echo “<ul>”;
$args2 = array(
‘orderby’ => ‘name’,
‘parent’ => 2,
‘hide_empty’ => FALSE

// ‘taxonomy’ => $taxonomy

$categories2 = get_categories( $args2 );
foreach ($categories2 as $category2) {
$catid = $category2->term_id;
// echo “subcatid “.$catid;   // To display category id

echo $category2->cat_name;

} }


Ouput :


About the author



Vishwas Hegde is the architect of ProCodersOnline.com. I'm a Software Engineer and technology enthusiast person who loves to learn and explore new things and technologies. When i'm not writing content for my websites, I love to travel and explore the nature.

Add Comment

Click here to post a comment