Display a category only when it has posts

Solution:1

Hook with get_terms will display a terms/category only when it has posts

Add this code in WP theme’s functions.php

E.g (domain.com/wp-content/themes/yourThemeName/functions.php )

add_filter('get_terms', 'get_terms_filter', 10, 3);
function get_terms_filter( $terms, $taxonomies, $args )
{
    global $wpdb;
    $taxonomy = $taxonomies[0];
    if ( ! is_array($terms) && count($terms) < 1 )
        return $terms;
    $filtered_terms = array();
    foreach ( $terms as $term )
    {
        $result = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts p JOIN $wpdb->term_relationships rl ON p.ID = rl.object_id WHERE rl.term_taxonomy_id = $term->term_id AND p.post_status = 'publish' LIMIT 1");
        if ( intval($result) > 0 )
            $filtered_terms[] = $term;
    }
    return $filtered_terms;
}

For ignore sticky posts on frontend set ignore_sticky_posts to true in main query

add_action('pre_get_posts', '_ignore_sticky');

function _ignore_sticky($query)
{
    // Only for Front end
    if (!is_admin() && $query->is_main_query())
        $query->set('ignore_sticky_posts', true);
}

Solution:2

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.

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.

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:

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.