How to Dynamically Exclude Empty Categories From Navigation Menus in WordPress

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 you how to implement your plan.

For this solution we will use the filter wp_get_nav_menu_items 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 receive three arguments, but we’ll only use the first one:

$ items – an array of menu items
$ menu – menu object
$ args – arguments passed to wp_get_nav_menu_items () function
First, we access $ wpdb, which will allow us to execute direct SQL queries. We then use the get_col method to get an array containing the IDs of all empty terms in the database. Then, through the loop, we process all the $ items menu items, and if the menu item is a taxonomy term and its ID is in the list of empty terms, then we remove it.

All it takes for the code to work is to add it to your theme’s functions.php file or to your WordPress site plugin:

add_filter( 'wp_get_nav_menu_items', 'gowp_nav_remove_empty_terms', 10, 3 );
function gowp_nav_remove_empty_terms ( $items, $menu, $args ) {
	global $wpdb;
	$empty = $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, $empty ) ) ) {
			unset( $items[$key] );
		}
	}
	return $items;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Ads Blocker Image Powered by Code Help Pro
It looks like you\'re using an Adblock. That\'s okay. Who doesn\'t😔

But without advertising, we can\'t keep making this awesome.
Please disable Adblock for our domain🙏

Refresh