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:

Setting a custom permalink in WordPress allows you to create a specific URL structure for your website's posts and pages. This can be helpful in terms of search engine optimization (SEO) and user-friendly navigation. Here is how you can set a custom permal...
To install WordPress on Docker, follow these steps:Choose a directory on your computer where you want to store your WordPress files.Open a terminal or command prompt and navigate to the chosen directory.Create a new directory for your WordPress installation us...
Filtering posts in WordPress by category allows you to display only the posts that belong to a specific category or categories. This can be helpful if you want to create custom pages or sections on your website that focus on specific topics.To filter posts by ...