WooCommerce Hide product when variation with specific attribute doesn't exist

Viewed 284

All my products are variable, all of them have 4 variations, one for each region.

Users can select which of the 4 regions they want to see prices for when browsing.

The issue is that for some products, one or more variations/regions aren't enabled or out of stock so users end up seeing "out of stock" products while browsing.

I want to filter/hide products that don't have the variation type they have selected, site-wide (search included).

The selected variation type the user clicked is accessible in the session cookie. I think this filter might be a good start:

add_filter( 'woocommerce_product_query_meta_query', 'shop_only_available_products', 10, 2 );

so if $_COOKIE['region'] not in [list of variations for product] then -> hide

Product 1
Variant 1 (NA) - IN STOCK
Variant 2 (EU) - IN STOCK
Variant 3 (ASIA) - OUT OF STOCK
Variant 4 (AFR) - IN STOCK

User has selected to browse by ASIA, so I want to hide this product because ASIA is out of stock. It has to account for what the user has selected.

1 Answers
add_filter('woocommerce_variation_is_active', 'disable_variation_when_out_of_stock', 10, 2);

function disable_variation_when_out_of_stock($grey_out, $variation) {
    if (!$variation->is_in_stock()) {
        return false;
    } else {
        return true;
    }
}

You can disable variant selection for out stock variations using the above code snippet.

Related