Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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 at 7:57

1 Answer 1

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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