I've been researching this and had no luck so far.
I have a WooCommerce store with a main menu showing product categories (product_cat) and brands (yith_product_brand) which is a custom taxonomy.
I want to hide categories and brands if they are empty. Do you know a way to achieve this, either by using a plugin or adding a function/filter to the functions.php file? If so any help would be much appreciated.
Thanks in advance.
I've been researching this and had no luck so far.
I have a WooCommerce store with a main menu showing product categories (product_cat) and brands (yith_product_brand) which is a custom taxonomy.
I want to hide categories and brands if they are empty. Do you know a way to achieve this, either by using a plugin or adding a function/filter to the functions.php file? If so any help would be much appreciated.
Thanks in advance.
Not sure about the custom taxonomy, however I have used this code before to remove empty categories. You can add it to functions.php.
add_filter( 'wp_get_nav_menu_items', 'nav_remove_empty_category_menu_item', 10, 3 );
function nav_remove_empty_category_menu_item ( $items, $menu, $args ) {
global $wpdb;
$nopost = $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, $nopost ) ) ) {
unset( $items[$key] );
}
}
return $items;
}
function remove_empty_category_from_menu_item( $items, $menu, $args ) {
// Get all categories that have products
$categories_with_products = get_categories( array(
'taxonomy' => 'product_cat',
'hide_empty' => true,
'hierarchical' => true,
) );
// Extract category IDs and add them to $categories_to_keep array
foreach ( $categories_with_products as $category ) {
$categories_to_keep[] = $category->term_id;
}
// Loop through each menu item
foreach ( $items as $key => $item ) {
// Check if the menu item is of type 'taxonomy' and object is 'product_cat'
if ( 'taxonomy' == $item->type && 'product_cat' == $item->object ) {
// If the menu item's object_id is not in $categories_to_keep array, remove it
if (!in_array( $item->object_id, $categories_to_keep ) ) {
// unset frome the menu
unset( $items[$key] );
}
}
}
return $items;
}
add_filter( 'wp_get_nav_menu_items', 'remove_empty_category_from_menu_item', 10, 3 );