Wordpress How-To

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 their Categories, Tags and Taxonomies. One of the major difference between Categories and Tags is that Categories can have Subcategories or child categories nor the tags.

By default WordPress will be having one category called “Uncategorized”  which cant be deleted, because It you have missed to create new category WordPress will consider’s the POST/Product as  Uncategorized. When you create a new category, a page is automatically generated that includes all the posts assigned to that particular category.

In this article, we will show you how to display Categories and Subcategories, this is a simple way as we have the ready made code for you. as we have tailor made code just paste the below code in where ever is required.

Let’s get started : 

$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
);
?>

<?php
$args2["parent"]=$category->term_id;
$categories2 = get_categories( $args2 );
foreach ($categories2 as $category2) {
$catid = $category2->term_id;
// echo “subcatid “.$catid;   // To display category id

echo $category2->cat_name;

} }

}

 

Ouput :

Main-Category
Subcategory-01
Subcategory-02

If you found any difficulties in doing this please write a comment in the below comment box.

Happy Coding 🙂

About the author

Vishwas

A coder who is trying to solve some problems via "Procoders", Software Engineer By Profession, WEB Enthusiast, Hobby Blogger. I love to share Tech Ideas and like to learn and explore new things and Technologies.

Add Comment

Click here to post a comment