Woocommerce Set Default Variation Of Variable Product

161 views Asked by At

I Write Below Function For Set Default Woocommerce Variation By Lowest Price and In Stock. But Problem is This Function Work Fine When A User Request a Product Page For Second Request ! When the first time A Product be displayed, Default Variation Not Work Right ! This Update Default Variation Of Variable Product after first request !

add_action( 'woocommerce_before_variations_form', 'set_default_variation_job' );
function set_default_variation_job() {
   
   
    $product_id = get_the_ID();
    $product    = wc_get_product($product_id); // Get the variable product object

    // Only for variable products & Check if default variation has been updated
    if ( $product->is_type( 'variable' ) ) {

        $active_prices  = $product->get_variation_prices()['price']; // Array of variation Id / active price pairs
            foreach ($active_prices as $key => $value) {
                 $variation = wc_get_product($key);
                if($value == "0" || !$variation->is_in_stock()){
                    unset($active_prices[$key]);
                }
            }
        asort($active_prices, SORT_NUMERIC);    

        $variations_ids = array_keys($active_prices); // Array of variations IDs
        $variation_id   = strval($variations_ids[0]); // Get the variation with the Lowest price
        
        $variation = wc_get_product( $variation_id ); // Get an instance of the WC_Product_Variation object
        $default_attributes = $variation->get_variation_attributes(false); // Get formatted variation attributes         
        update_post_meta($product_id, '_default_attributes', $default_attributes);

         }
}

a Wrong Woocommerce Default Variation

1

There are 1 answers

0
Eugen Belousov On

woocommerce_before_variations_form is too late, page already rendered at that time. Try template_redirect or wp hook.