Ecommerce Shopify WordPress Discussion

Woocommerce Set Default Variation Of Variable Product

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
woocommerce_before_variations_form is too late, page already rendered at that time. Try template_redirect or wp hook.

December 30, 2023

Our products

The help you need, when you need it

App by Turbo Engine

3 apps • 5.0 average rating

Turbosify Speed Booster

5.0 (7)
Get better conversions by optimizing shopify store Google page speed Installed

Turbosify Translator for Wordpress Woocommerce

5.0 (74) Free Wordpress Woocommerce Plugin
Translate your wordpress website to multiple language within 1 click, no configuration needed, no No technical required

Grow your business here

Whether you want to sell products down the street or around the world, we have all the tools you need.