fourgood
fourgood

Reputation: 187

wordpress wp_nav_menu hide empty categories

im am searching for a way to hide empty categories from a custom menu in wordpress?

I have build a massive hierarchy and now i am going to fill the categories one after one. But until I have put a post in it, I want to hide it from the menu.

Seems that I need something similar like hide_empty=1 for "wp_list_categories" but now for "wp_nav_menu".

Upvotes: 0

Views: 2782

Answers (3)

Glenn Geiger
Glenn Geiger

Reputation: 48

The accepted answer is effective, but it destroyed the menu structure for me, meaning the ul > li > ul.sub-menu > li > and so on. Rather than unset the item, I added a new class to the item->classes array to hide it in css.

if (!is_admin()) add_filter('wp_get_nav_menu_items', 'wp_nav_remove_empty_terms', 10, 3);

function wp_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] );
      $item->classes[] = 'hide';
    }
  }
  return $items;
}

Upvotes: 0

Surender
Surender

Reputation: 61

Add the following code to child theme's functions.php file:

/*  
 *  Hide empty categories from nav menus
 */
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;
}

Upvotes: 1

Riyaz
Riyaz

Reputation: 99

We can't compare "wp_list_categories" with "wp_nav_menu". We don't have that hide_empty option for "wp_nav_menu". Only solution is we have to write our own menu or else we have to use hooks for "wp_nav_menu".

Upvotes: 0

Related Questions