Hide empty product categories from Main Navigation in WooCommerce

WordPress
You can of course add unlimited WooCommerce Product Categories into your main navigation. But sometimes they get empty because of Stock change or similar. If you automatically want to hide empty product categories in your WordPress Navigation place the code below into your functions.php file.
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 );
        }
    }
    return $items;
}

One thought on “Hide empty product categories from Main Navigation in WooCommerce

  1. Jon-Paul Smith says:

    Hi there,
    Is it possible to hide product categories and / or subcategories if the products in them are out of stock please?

    So for example I have the ‘Out of stock visibility – Hide out of stock items from the catalog’ in Woocommerce settings checked, so out of stock products are not being displayed.

    However I also have a category for ‘Elektra Comic Books’ that has two subcategories:

    Elektra Vol 3 (2014)
    Elektra: Black, White & Blood (2022)

    Elektra Vol 3 (2014) has a comic in stock, but Elektra: Black, White & Blood (2022) has no comics in stock and displays the ‘No products were found matching your selection.’ message when entered.

    Is there some code I can use so that the Elektra: Black, White & Blood (2022) subcategory (or any other subcategory that has no products in stock) is not displayed, but if new stock is added it will become visible / available again?

Leave a Reply

Your email address will not be published. Required fields are marked *

We use cookies to give you the best online experience. By agreeing you accept the use of cookies in accordance with our cookie policy.

Close Popup
Privacy Settings saved!
Privacy Settings

When you visit any web site, it may store or retrieve information on your browser, mostly in the form of cookies. Control your personal Cookie Services here.

These cookies are necessary for the website to function and cannot be switched off in our systems.

Technical Cookies
In order to use this website we use the following technically required cookies
  • wordpress_test_cookie
  • wordpress_logged_in_
  • wordpress_sec

Decline all Services
Save
Accept all Services