How to Display a Category only if it has Posts in WordPress
This snippet that we are sharing in this article is helpful in very custom designs. By default you can use wp_list_categories function to display categories, and it only displays categories if it has posts. Sometimes when you are customizing WordPress, you might need to use it this way. When we were working on a client’s project, we found a need for this snippet, therefore we are sharing it for anyone else who can use it.
<?php if (get_category('17')->category_count > 0) echo get_category('17')->cat_name; ?>
In the method above we are specifying the category ID for very specific category if you want to check, but you can do this with all categories also. Just paste the snippet below where you want it.
<?php foreach (get_categories() as $category){
if ($category->count > 0){
echo $category->cat_name;
}
} ?>
Now how would you use it? Well sometimes you have a category with a specific name, but you want to display the link with a different anchor text, and you only want to display it if it has posts, this way can be handy. So for instance in your navigation menu, you can enter something like this:
<?php if (get_category('17')->category_count > 0) echo "<a href=\"".get_bloginfo('home')."/category/news/\">Blog</a>"; ?>
This will check if category 17 has any posts, if it does, then it will display the navigation menu item called Blog, otherwise it would not.
It’s very simple and easy, but for those new developers it can be helpful.
Comments
7 Responses to “How to Display a Category only if it has Posts in WordPress”Share Your Opinions
Tell us what you're thinking...
and if you want a pic to show with your comment, then get gravatar!
Please make sure that you have read our Comment Policy.











It seems interesting but I seriously didn’t understand it. When we can name/rename a category from news to Blog. Whats the thing else than showing only if it has posts? *confused :s
This is only for very customized settings, but it is still good to know for those who does not. Yes you can rename a category, but how many times. If you have 7 custom page templates where you want to call one category 7 different names, then how would you go about it. For Sales / Splash pages, this will help.
ah thanks, now I can say its pretty useful. Thanks a ton !
Excuse me if I’m wrong but doesn’t it do this already in the most recent versions?
Read the first two lines of the post. We already mention that using the wp-list-cats, yes it does, but if you are doing some more customization and need it hard coded without calling a function, then this is the way you will go.
really useful, thanks. I have placed a link back to this on my own blog so that I can share it with others
Thanks Michelle