This is a quick solution to how to disable out of stock variations in variation select fields. By default, WooCommerce doesn’t grey out any variations that are out of stock – it allows the user to select the variation first, then lets them know it’s out of stock.

However, you may prefer to see something like the image below, with out of stock options disabled and displaying ‘sold out’ text.

There are a lot of suggested solutions out there for how to disable out of stock options, many involving complicated JavaScript. It’s not necessary. Just add the following snippet to your functions.php file or wherever you add snippets:

/**
* Disable out of stock variations
* https://github.com/woocommerce/woocommerce/blob/826af31e1e3b6e8e5fc3c1004cc517c5c5ec25b1/includes/class-wc-product-variation.php
* @return Boolean
*/
function wcbv_variation_is_active( $active, $variation ) {
if( ! $variation->is_in_stock() ) {
return false;
}
return $active;
}
add_filter( 'woocommerce_variation_is_active', 'wcbv_variation_is_active', 10, 2 );

That’s all you need to do. The function uses a standard WooCommerce filter – woocommerce_variation_is_active, checks whether the variation is in stock, and returns false if it’s not. WooCommerce does the rest.

Oh, and don’t forget to ensure that you are managing your variations’ stock.

WooCommerce manage variation stock

 


Do you develop plugins?

You should try Wisdom, a plugin designed specifically for plugin developers that allows you to track your plugin's usage and provides invaluable data on how your plugin is being used. Find out more.

Leave a Reply

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