Display all subcategories from a specific category on selected Category Archive page ?

Currently wordpress shows list of all posts for a specific category if user clicks on that category, this is absolutely fine if there are no subcategories in that selected category, but if we have some more subcategories then all the posts from those subcategories gets mixed making it difficult for user to navigate to right category, to make this easier we will write some custom code into archive page which will make user navigation between categories much easier. Same code has been used on this website.

Related: If you are also looking for Adding Categories on home page, visit post “How to display WordPress Categories on home page of website

Login to your hosting server and modify open wp-content/themes/YOUR_THEME/archive.php to add below code as,

<?php
$category_name = single_cat_title("", false);
$category_id = get_cat_ID($category_name);
$categories = get_categories(array('child_of' => $category_id));
foreach($categories as $category) {
    echo '<a href="' . get_category_link( $category->term_id ) . '">' .       $category->name.'</a><br><hr> ';
}
?>

here, using “single_cat_title” function we get the selected category name and from name using function “get_cat_ID” we get the category ID and using function “get_categories” we get all the subcategories of that category and are displayed using foreach loop.

NOTE: As we observed “single_cat_title” doesn’t work properly if we have special characters like hyphen “-” in category name. For example, to make it working we had to rename category “Content Management System – CMS” to “Content Management System” by removing hyphen.

Follow Lynxbee

Leave a Reply / Ask Question