phparrayswordpresswoocommerceproduct-variations

Set the highest priced variation as default in WooCommerce variable products


I have a lots of products with variations in my WooCommerce installation. None of them are pre-selected as default when user browses to any product page.

Manually selecting them would be a tedious job. Additionally, new products and variations are imported automatically on a daily basis using an SQL script.

I would like to have pre-selected product variation with the highest price for any user that browses to any product page which has variable product.

How can that be done?


Solution

  • Update - 2023 (code simplification and optimization)

    Here it is an automated solution, that will do the job one time, each time a variable product is called/browse by a customer.

    The variable product will be updated with a default variation that has the highest price.

    This will be done once only, as I set a custom post meta key/value each time a variable product has been updated.

    The code:

    add_action( 'template_redirect', 'set_default_variation_job' );
    function set_default_variation_job() {
        if ( ! is_product() || is_admin() ) return;
        
        $product_id = get_the_ID();
        $product    = wc_get_product($product_id); // Get the variable product object
    
        if( ! is_a( $product, 'WC_Product' ) return; // Exit if is not a product object
    
        // Only for variable products & Check if default variation has been updated
        if ( $product->is_type( 'variable' ) && ! $product->get_meta('_default_variation_updated') ) {
    
            $active_prices  = $product->get_variation_prices()['price']; // Array of variation Id / active price pairs
            $variations_ids = array_keys($active_prices); // Array of variations IDs
            $variation_id   = end($variations_ids); // Get the variation with the highest 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         
            
            // Set the default variation attributes in the Variable product
            $product->set_default_attributes( $default_attributes );
    
            // Set a meta data flag to avoid update repetitions
            $product->update_meta_data('_default_variation_updated', '1');
            $product->save(); // Save the data
        }
    }
    

    Code goes in functions.php file of your child theme (or in a plugin). Tested and works.

    Related: Set the variation with highest discount percentage as Default in WooCommerce