Website Templates Search

Get category which has posts - WordPress Example

  • Click to view live demo By Admin
  • Click to view live demo Sep 15, 2017

In this article we are going to show you how to display a category if it has post. You can use “WP_LIST_CATEGORIES()” function to display categories.

“WP_LIST_CATEGORIES()” only display those categories who has its own posts. Sometimes when you customizing your wordpress you must to use it.

Sometimes we were working on any project we found a need for this code.

<?php if (get_category('30')->category_count > 0) 
  echo get_category('30')->cat_name; 
 ?> 

In the above method we are specifying the category ID for a specific category if you want to check.

You can do this with all categories:

code :

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

How would you use it. In somecases, you have a category with a name but you want to display the link with a different anchor text.

And you only want to display if it has posts.

Code :

<?php if (get_category('30')->category_count > 0) 
echo "<a href=\"".get_bloginfo('home')."/category/news/\">Blog</a>"; 
?>

This will check if category 30 has any posts, if it does, then it will display the navigation menu item called blog, otherwise it would not.