Do you want to show subcategories on your category pages in WordPress?
WordPress lets you organize your posts using categories and subcategories. Showing these subcategories on your category pages can help your visitors find what they’re looking for more easily.
In this article, we’ll explain how to display subcategories on category pages in WordPress.
Why Display Subcategories on Category Pages?
Organizing your posts into categories and subcategories improves navigation and helps search engines understand your site better, which can bring more traffic. For instance, if you have a main category called Sports, you might create subcategories like NFL, NBA, and MLB under it.
When visitors click on the Sports category, they see all posts in Sports and its subcategories, but they don’t see a list of these subcategories, making it hard to filter down to specific ones like NFL or NBA.
By showing a list of subcategories on your category pages, you can improve navigation. For example, users can easily switch from all Sports posts to just NFL posts and then to NBA.
Let’s see how to do this in WordPress.
How to Display Subcategories on Category Pages in WordPress
To show subcategories on your category archive pages, you need to add some code to your theme files. If you need help adding code, refer to our guide on how to paste snippets from the web into WordPress.
- Locate or Create category.php File:
- Go to your theme’s folder and look for
category.php
. - If it’s not there, duplicate
archive.php
and name itcategory.php
.
Note: If your theme doesn’t have
category.php
orarchive.php
, you might be using a WordPress theme framework and need to createcategory.php
manually. Check our guide on creating custom archive pages for more info. - Go to your theme’s folder and look for
- Add Code to category.php:
- Open
category.php
. - Add the following code just before the loop:
- Open
if (is_category()) {
$this_category = get_category($cat);
}
?>
<?php
if($this_category->category_parent) {
$this_category = wp_list_categories(‘orderby=id&show_count=0&title_li=&use_desc_for_title=1&child_of=’ . $this_category->category_parent . “&echo=0”);
} else {
$this_category = wp_list_categories(‘orderby=id&depth=1&show_count=0&title_li=&use_desc_for_title=1&child_of=’ . $this_category->cat_ID . “&echo=0”);
}
if ($this_category) {
?>
<ul>
<?php echo $this_category; ?>
</ul>
<?php } ?>
- Save Changes:
- Save the changes to your
category.php
file.
- Save the changes to your
Now, when you visit a category page, you’ll see a list of subcategories. For example, on a demo site, the Sports category page will show links to the NFL, NBA, and MLB subcategories. Clicking on the NFL link will take you to the NFL subcategory page, where you can still see links to the other Sports subcategories, making it easy to switch between them.
By following these steps, you can make your WordPress site more user-friendly by displaying subcategories on your category pages.