Display Child Categories of Selected Parent Category in WordPress Category Page

How to display WordPress child categories of selected parent categoryDealing with WordPress categories is a repeating task for wordpress developers, although it’s sometime difficult for beginers to achieve the required result with these categories. I am writing this post to give you a quick guide on displaying child categories of a selected category in category page.

NOTE : this code can be used in any of wordpress page template with minor modifications.

First take a look at the complete code (ready to copy and paste in your plugin/theme template).

if(is_category()){

$this_category = get_category($cat);
 $parent_cat_id =$this_category->cat_ID; // term id/category id of parent category
 $taxonomies = array(
 'taxonomy' => 'category' );

$args = array( 'child_of' => $parent_cat_id);

$childCategories = get_terms($taxonomies, $args);
 if (sizeof($childCategories)>0)
 {

echo ' <div class="categories"> ';
 echo '<p> Sub Categories of '. get_cat_name( $parent_cat_id ) .'</p>';

foreach ( $childCategories as $child ) {

$child_link = sprintf( '<a href="%1$s" alt="%2$s">%3$s</a>', esc_url( get_category_link( $child ->term_id ) ),
 esc_attr( sprintf( 'View all posts in %s', 'textdomain' ), $child ->name ),
esc_html( $child ->name ));

echo sprintf( $child_link );
 }

echo '</div><!-- categories div end-->';

}// end if

Code Explanation:

if(is_category) confirms that we are on category page (category.php).

get_category() function takes one required parameter which is category ID or category row object. We are using this to get the id of currently selected category in order to check if it has any child categories.

get_category($cat) , $cat is a wordpress global variable which we can access in category page, containing selected category data.

get_terms($taxonomies,$args) , used to retrieve the child categories. $taxonomies and $args are two arrays of parameters, in $taxonomies array we require only categories thus have listed only category,, if you want to get your custom taxonomy you can replace the category with your taxonomy name like this,
$taxonomies=array ('taxonomy'=>'your_custom_taxonomy');
and in the $args array we are only interested in the child categories so we have entered only child_of parameter.

get_cat_name($parent_cat_id) returns name of the category and accept id of the category as a parameter. the code down below is pretty self explanatory..

if you have any problem/issue any where in the code do ask in comments and i will be glad to help.




Leave a Reply

Your email address will not be published. Required fields are marked *


1406 Views