Default to Random 'In Stock' Variation on WooCommerce
🗓When you're working with 'Variable Products' in WooCommerce you're able to select a 'Default Variation' that'll always be preselected when a user first visits the page. While I imagine for most use cases this is enough I work with quite a few stores that have tons of variations and they're often out of stock. This resulted in a lot of situations where users would have an out of stock product preselected, which wasn't great.
I poked around online a bit and couldn't find a good solution for fixing this, so I decided to put together a quick snippet that would do the trick:
function zf_set_default_variation_to_any_instock_product() {
// Get Product Data
global $product;
// Don't Do Anything If Not Variable Product
if ( $product->is_type( 'variable' ) ) {
// Get Array of In Stock Variations
$in_stock_variations = $product->get_available_variations();
// Don't Do Anything If 100% Out Of Stock
if(count($in_stock_variations) > 0) {
// Format Variation Correctly By Removing attribute_ Prefix
$in_stock_variations_formatted = array_combine(
array_map(
function($k) { return str_replace("attribute_", "", $k); },
array_keys($in_stock_variations[0]['attributes'])
),
array_values($in_stock_variations[0]['attributes'])
);
// Set First In Stock as Default
$product->set_default_attributes($in_stock_variations_formatted);
}
}
}
add_action( 'woocommerce_before_add_to_cart_form', 'zf_set_default_variation_to_any_instock_product' );
This isn't the most flexible snippet in the world - I'm sure it could be more robust - but it did the trick for what we needed and I thought I'd share. It'll go through all of variations available and set the first one found as the default. This will completely override the 'Default Variation' functionality, so, if you're hoping to only use this as a fallback you'll likely need to build upon it a bit.
You can easily add this to your functions.php file - or - using the Code Snippets plugin.
Hopefully that saves someone a little time! 😁
———