Do you want your WordPress posts to just show the parent category?
Most WordPress themes list all categories linked with a post by default. Some users, on the other hand, may only want to see the parent category and not the child categories.
We’ll show you how to change the WordPress post loop so that only the parent category is displayed on a single post in this article.
When should you just show the parent category in WordPress?
Many website owners utilize parent and child categories to organize their sites.
For example, a travel blog might categorize vacation destinations into categories, with each area serving as the parent category and cities serving as the child categories.
The category() template tag is now used by most WordPress themes to list all categories linked with a post.
This tool is useful, but it displays all categories in alphabetical order and ignores the parent/child relationship entirely.
That being said, let’s look at how to modify this behavior so that the WordPress loop only shows the parent category.
In the WordPress Post Loop, just the parent category is displayed.
You’ll need to edit your WordPress theme files for this guide. Check out our post on how to copy and paste code snippets in WordPress if you haven’t done so before.
To begin, add the following code to your theme’s functions.php file or a site-specific plugin’s functions.php file.
This code just creates the wpb get parent terms function (). This function will only show parent categories by default.
Then, in the WordPress theme files where you wish to display the parent category alone, include this function.
See our WordPress template hierarchy cheatsheet for novices to figure out which template file to look into.
Within the WordPress loop, you’ll be looking for the category(); template tag. Once you’ve located it, you’ll need to replace it with the code below:
This code will only show the parent category. If you have numerous parent or independent categories, then all of them will be displayed.
This code will also work for other taxonomies. For example, WooCommerce product categories or any other custom taxonomy you might have.
Simply change the code to look like this:
This code will show product categories in a WooCommerce store, but only the parent or standalone categories for each product.
If you want to show a custom taxonomy, replace product cat with the name of the custom taxonomy.
We hope that this article has shown you how to just show the parent category for your WordPress posts. You might also be interested in our guide to creating custom WordPress pages without writing code or these other WordPress category hacks and tricks.