Wordpress

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.

1 <?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.

1 <?php foreach (get_categories() as $category){
2 if ($category->count > 0){
3 echo $category->cat_name;
4 }
5 } ?>

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:

1 <?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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s