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.

Seraphinite AcceleratorOptimized by Seraphinite Accelerator
Turns on site high speed to be attractive for people and search engines.