Family Encyclopedia >> Electronics

WordPress: Display Categories Only If They Have Posts (Proven Snippet)

As experienced WordPress developers with years of custom theme projects under our belt, we've relied on this simple technique to conditionally show categories in navigation menus and layouts. By default, wp_list_categories() handles this, but for precise control, use these PHP snippets.

For a specific category (e.g., ID 17):

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

To loop through all categories:

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

Practical example: Custom nav link with anchor text "Blog" that only appears if category 17 has posts. Add the full link for functionality:

<?php if (get_category(17)->category_count > 0) echo '<a href="' . get_category_link(17) . '">Blog</a>'; ?>

This keeps your menus clean and dynamic—ideal for client sites where categories evolve. Simple yet powerful for developers at any level.