How To Dynamically Exclude Empty Categories From The Navigation Menu In WordPress

2 minutes read

Recently, one of our readers asked how you can exclude categories from the navigation menu on the fly if there are no entries in the category. In this article we will show how to implement our plans.

For this solution we will use the wp_get_nav_menu_items filter and the global $ wpdb object [ codex ]. They will help us remove empty terms from any taxonomies.

The wp_get_nav_menu_items filter is applied to the array of menu items in the wp_get_nav_menu_items () [ codex ] function and our filtered function will take three arguments, but we will only use the first one:

  1. $ items – an array of menu items
  2. $ menu – menu object
  3. $ args – arguments passed to wp_get_nav_menu_items () function

First we refer to $ wpdb , which will allow us to execute direct SQL queries. Then we use the get_colmethod to get an array containing the ID of all empty terms in the database. Then we cycle through all the items in the $ items menu , and if the menu item is a taxonomy term and its ID is in the list of empty terms, then we remove it.

All that is needed for the code to work is to add it to the functions.php file of your theme or to the plugin for the WordPress site :

1 add_filter( 'wp_get_nav_menu_items''gowp_nav_remove_empty_terms', 10, 3 );
2 function gowp_nav_remove_empty_terms ( $items$menu$args ) {
3     global $wpdb;
4     $empty $wpdb->get_col( "SELECT term_taxonomy_id FROM $wpdb->term_taxonomy WHERE count = 0" );
5     foreach $items as $key => $item ) {
6         if ( ( 'taxonomy' == $item->type ) && ( in_array( $item->object_id, $empty ) ) ) {
7             unset( $items[$key] );
8         }
9     }
10     return $items;
11 }
Facebook Twitter LinkedIn Telegram Pocket

Related Posts:

Do you want to add notifications to the admin panel in WordPress? Admin notifications are used by the WordPress core, themes, and plugins to display warnings, notifications, and important information for users on the screen. In this article, we will show you h...
Would you like to turn off email notification about automatic WordPress update? By default, WordPress sends email notifications to inform you that security updates have been installed on your site. Recently, a reader asked if there was a way to disable these e...
Would you like to remove the “WordPress site” link from the footer of your site? Recently, one of our readers asked if it was possible to remove copyrights from the footer in WordPress themes. In this article, we will show you how to remove a link for a WordPr...