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:
- $ items – an array of menu items
- $ menu – menu object
- $ 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 ) { |
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 ) ) ) { |