[SOLVED] Removing 'Empty' Categories/SubCategories from a WooCommerce NavBar in WordPress

Issue

The code below allows a user to hide ’empty’ category and subcategory levels on a WooCommerce site when there are no products within a category level, but I have realised this is not the correct way to code this function as it uses the ‘product id’ as a reference, when really it needs to be referencing and checking itself against the ‘stock levels’ of any products that may be in said category/subcategory level instead.

Is anyone able to amend the following code to check against stock levels rather than product id’s? I have tried, but without success.

function nav_remove_empty_category_menu_item ( $items, $menu, $args ) {
    if ( ! is_admin() ) { 
        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;
}

add_filter( 'wp_get_nav_menu_items', 'nav_remove_empty_category_menu_item', 10, 3 );

Solution

This answer was actually compiled for me in the end by the amazing Md. Mehedi Hasan so full credit goes to him!

function nav_remove_empty_category_menu_item ( $items, $menu) {

    if ( ! is_admin() ) {
        
        $args = array(
        'hide_empty' => false,
        'hierarchical' => true,
    );

    $product_categories = get_terms( 'product_cat', $args );

    $exclude = array();
    foreach ( $product_categories as $category ) {

        $posts         = get_posts( array( 'post_type' => 'product', 'posts_per_page' => -1, 'product_cat' => $category->slug, 'fields' => 'ids' ) );
        $show_category = false;

        foreach ( $posts as $post ) {

            $product         = new wC_Product( $post );
            $visible_product = $product->is_visible();

            if ( true === $visible_product ) {
                $show_category = true;
                break;
            }

        }

        if ( false === $show_category ) {
            $exclude[] = $category->term_id;
        }

    }

        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, $exclude ) ) ) {

                unset( $items[$key] );

            }

        }

    }

    return $items;

}

add_filter( 'wp_get_nav_menu_items', 'nav_remove_empty_category_menu_item', 10, 3 );

Answered By – LionHeart-Nerd

Answer Checked By – Timothy Miller (BugsFixing Admin)

Leave a Reply

Your email address will not be published.