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.

Tables can't be imported directly. Please insert an image of your table which can be found here.

1

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.

Tables can't be imported directly. Please insert an image of your table which can be found here.

1 2 3 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:

Tables can't be imported directly. Please insert an image of your table which can be found here.

1

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.

Was this article helpful?
0 out of 0 found this helpful