How to Gray-out Out of Stock Variations
In this tutorial we will try to make specific variations (out of stock ones) in the variations dropdown list not selectable:

By default WooCommerce allows to select a variation even if it is out of stock and as a result we have a frustrated customer who sees this sad smiley instead of an active “Add to cart” button:

The definition of out-of-stock variation:
- “Stock status” is set to “Out of stock”,
- “Stock quantity” is equal to 0 when the stock is managed on the variation level,
- “Stock quantity” is equal to 0 when the stock is managed on the product level.
In all these cases is_in_stock()
method will return false
and that’s exactly what we need and what we are going to use in the code snippet below.
Don’t forget that there is an option in WooCommerce > Settings > Products > Inventory which allows to hide out of stock variations from the dropdown list:

add_filter( 'woocommerce_variation_is_active', 'rudr_variation_grey_out', 25, 2 );
function rudr_variation_grey_out( $active, $variation ) {
// here we go
if( ! $variation->is_in_stock() ) {
$active = false;
}
return $active;
}
If you don’t know where to use this code, please check this guide.
If you’re using this code to display variations as radio buttons, there is also some additional JavaScript you need to add to make it work:
$( document ).on( 'woocommerce_update_variation_values', function() {
$( '.rudr-variation-radios input' ).each( function( index, element ) {
const radio = $(element)
const radioName = radio.attr( 'name' )
const radioValue = radio.attr( 'value' )
radio.removeAttr( 'disabled' )
if( $( 'select[name="' + radioName + '"] option[value="' + radioValue + '"]' ).is( ':disabled' ) ) {
radio.prop( 'disabled', true )
}
})
})
Now it is perfect:


Misha Rudrastyh
Hey guys and welcome to my website. For more than 10 years I've been doing my best to share with you some superb WordPress guides and tips for free.
Need some developer help? Contact me