WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm trying to build a menu which can be administered from the menu editor, but gets filtered before being output.

More specifically the menu contains Woocommerce product categories, organised into a hierarchy, and I want to exclude empty categories from being output.

This will allow administrator to set the hierarchy once and have the menu reflect which products are currently in stock dynamically.

After follwoing ENTHUSIAST's comment about a similar thread I have the code below but am not getting the right result. All items are being output

function exclude_empty_cat_menu_items( $items, $menu, $args ) {
  // Get a list of product categories that excludes empty categories
  $non_empty_categories = get_categories(array('taxonomy' => 'product_cat'));
  // Iterate over the menu items
  foreach ( $items as $key => $item ) {
    $is_empty = true;
    // check current item is in the non-empty categories array
    foreach ( $non_empty_categories as $key => $cat )
      if ($item->title == $cat->name) 
        $is_empty = false;
      // if it is empty remove it from array
      if ($is_empty) unset($items[$key]);
  }
  return $items;
}
add_filter( 'wp_get_nav_menu_items', 'exclude_empty_cat_menu_items', null, 3 );
share|improve this question
1  
This thread addresses a similar problem: wordpress.stackexchange.com/questions/31748/… – Enthusiast Jun 2 '14 at 7:57
up vote 0 down vote accepted

I had an error in the above code. $key used in both for loops.

Working code for filtering empty product categories out of menu items:

function exclude_empty_cat_menu_items( $items, $menu, $args ) {
  // Get a list of product categories that excludes empty categories
  $non_empty_categories = get_categories(array('taxonomy' => 'product_cat'));
  // Iterate over the menu items
  foreach ( $items as $key => $item ) {
    $is_empty = true;
    // check current item id is in the non-empty categories array
    foreach ( $non_empty_categories as $key2 => $cat )
      if ($item->title === $cat->name) 
        $is_empty = false;
      // if it is empty remove it from array
      if ($is_empty) unset($items[$key]);
  }
  return $items;
}
add_filter( 'wp_get_nav_menu_items', 'exclude_empty_cat_menu_items', null, 3 );
share|improve this answer

protected by Community Mar 9 at 14:08

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.