I need a code for woocommerce variable products that:
- Automatically selects the first variation that appears;
- But if the first variation is out of stock, automatically selects the variation that appears next, and so on;
- If all variations are out of stock, automatically selects the first variation.
I tried this snippet:
add_filter( 'woocommerce_dropdown_variation_attribute_options_args', 'filter_woocommerce_dropdown_variation_attribute_options_args', 10, 1 );
function filter_woocommerce_dropdown_variation_attribute_options_args( $args ) {
if ( count( $args['options'] ) > 0 ) {
$option_key = '';
$product = $args['product'];
if ( is_a( $product, 'WC_Product_Variable' ) ) {
foreach ( $product->get_available_variations() as $key => $variation ) {
$is_in_stock = $variation['is_in_stock'];
if ( $is_in_stock ) {
$option_key = $key;
break;
}
}
}
if ( is_numeric( $option_key ) ) {
$args['selected'] = $args['options'][$option_key];
}
}
return $args;
}
but doesn’t work in some products, like:
-
https://www.staging2.gataria.pt/produto/pronefra-virbac-suporte-da-doenca-renal-gatos-e-caes/
Here the second option is selected (180 mL) I don’t know why, because the first one is also in stock. -
https://www.staging2.gataria.pt/produto/arranhador-para-gatos-formato-arvore-derry/
Here the color BEGE is auto selected but it shouldn’t be because it’s out of stock, it should be CINZA ESCURO -
https://www.staging2.gataria.pt/produto/transportadora-para-gatos-com-abertura-frontal-e-no-topo-yoko/
Here the last options are auto selected and should be the first ones)
Anyone can help me? Thank you