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.
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
<?php
$args = array(
‘orderby’ => ‘name’,
‘parent’ => 0,
‘hide_empty’ => FALSE );
$args = array(
‘orderby’ => ‘name’,
‘parent’ => 0,
‘hide_empty’ => FALSE );
$categories = get_categories( $args );
$first = true;
foreach ($categories as $category) {
$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
$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
$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
Subcategory-01
Subcategory-02
Post a Comment