Family Encyclopedia >> Electronics

How to show a category only if it has posts in WordPress

This code snippet that we are sharing in this article is useful in very custom layouts. By default, you can use the wp_list_categories function to display categories, and it only displays categories if you have posts. Sometimes when you customize WordPress you may need to use it this way. When we were working on a client project, we found a need for this code snippet, so we are sharing it for anyone who might use it.

 category_count> 0) echo get_category ('17 ') -> cat_name; ?> 

In the above method, we specified the category ID for a very specific category if you want to check, but you can do it with all categories as well. Just paste the snippet below where you want it.

 cuenta> 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 show the link with a different anchor text, and you only want to show it if you have posts, this way can be useful. So, for example, in your navigation menu, you can enter something like this:

 category_count> 0) echo "Blog"; ?> 

This will check if category 17 has any posts, if it does then it will show the navigation menu item called Blog, otherwise it wouldn't.

It's very simple and easy, but for those new developers it can be useful.