Say you have a category page on which you’re asked to display all the posts that belong to that category’s subcategories. So far no sweat – a category page displays by default all its descendant posts, whether they belong directly to that category or any of its subcategories. But here’s the twist: say you have to display them in such a way that the subcategory names are displayed (challenge no. 1), and under each subcategory’s name you have to display all its posts (challenge no. 2).
Let me give an example of when you’d want to achieve such a thing: For instance, if you had a main category named “State-Wide Schools” which had subcategories, each of which was a city, and the posts were the schools in that city (each post detailing the properties of said school). Another case could be that the main category is a year, the subcategories are the months in that year, and the posts are events that happened that month.
Here is an illustration of the required category-page structure:
This post will take us step by step to achieving that goal.
Summary of How Categories Work in WordPress
Before we start, let’s quickly review how categories work in WordPress. As previously said, the default behavior of a category page is to display a list of all the posts in that particular category. The template file within the theme that’s in charge of rendering the category’s display is
If we want a certain category to be displayed differently, we target it with its own template file: the file’s name will start with the word
category, followed by a hyphen and then by either the category’s slug or its ID. This filename format enables the WordPress engine to recognize it as a specific category template. For example,
category-13.php will display the posts in the category whose ID is 13, and the
category-mycat.php would display the posts in the category whose slug is
In the case I’ll describe in this post, I decided to use the slug since the site admin has control over it and therefore it can be retained across different sites. This is as opposed to an ID which is automatically generated and therefore we’d have to change the template file’s name on each site to accommodate the different category IDs. That, of course, is not practical.
While this template file takes care of displaying the posts on the page, the other important issue is getting the data – as we noted before, by default WordPress doesn’t provide the data about subcategories in a category page.
There are a few different ways to retrieve the subcategories and the posts belonging to them—we can use the common WordPress functions, or we can construct a custom $wpdb query. This case required me to use a custom query, for reasons I’ll explain now.
Why a Custom $Wpdb Query?
This article was written by Lea Cohen and originally published on WPShout.