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 );