Woocommerce: set first product variable as default variation if not set
You can set a default for your variations when you create your product in WooCommerce, but if you forget it, it might be a good idea to have a fallback.
This little piece of code is based on a WooCommerce hook. Therefore it will work with any theme provided the hook is not excluded by the theme. The function sets the first variable as default if one is not set. The function must be added to the functions.php file in the theme and once the function is added it works.
There are several ways to store product metadata when saving the product in the backend. Since WooCommerce 3 you can use the following hook "woocommerce_admin_process_product_object" which the function is tied to. The function is executed when there is a product with variant properties and when you click "update". The function then checks if a default variation is set and if there are any valid product variations before it scrolls. If there is no default variation set and there are active variations, then it will update the post meta field "_default_attributes", which contains the data that stores the preselected variation. The update happens in a page load, and you will immediately see that a default variation has been set, that is if none has been set before.
/*--------------------------------------------------------------
Set first variable as default variation if not set
--------------------------------------------------------------*/
add_action('woocommerce_before_variations_form', 'default_variation_value_if_empty');
function default_variation_value_if_empty() {
if (!$product->is_type( 'variable' )) return false;
$product_variations = $product->get_available_variations();
if (empty($product_variations) || !empty($product->get_default_attributes())) return false;
$product_variations = $product->get_available_variations();
$attributes = (array_column($product_variations, 'attributes')[0]);
$label = explode('_',array_key_first($attributes))[1]; // Matcher label name
$new_default[$label] = sanitize_key(current($attributes));
update_post_meta($product->get_id(), '_default_attributes', $new_default);
}