Is there a function to cause empty categories not to show in menus?

Scenario: Clients can add or remove posts at will, but may not be comfortable (or even bother) adding categories to a menu.

Problem: This can cause empty categories to be displayed in menus.

Question: Is there a core function or resource that can be called from functions.php that will cause empty categories not to show on the front side even if they are showing as added in the dashboard.

Previous research: I have searched in both Google and this StackExchange for an answer. I may not be finding it by using the wrong search terms.

2 Answers
2


add_filter( 'wp_get_nav_menu_items', 'nav_remove_empty_category_menu_item', 10, 3 );
function nav_remove_empty_category_menu_item ( $items, $menu, $args ) {
    global $wpdb;
    $nopost = $wpdb->get_col( "SELECT term_taxonomy_id FROM $wpdb->term_taxonomy WHERE count = 0" );
    foreach ( $items as $key => $item ) {
        if ( ( 'taxonomy' == $item->type ) && ( in_array( $item->object_id, $nopost ) ) ) {
            unset( $items[$key] );
        }
    }
    return $items;
}

Please use the above code, it will unset the category which has No post.
Assuming that you were are managing Menu from Apperance->Menu.

Hope that helps 🙂

Leave a Comment