Get the Product Variation related to default attribute values in WooCommerce Get the Product Variation related to default attribute values in WooCommerce wordpress wordpress

Get the Product Variation related to default attribute values in WooCommerce


To get the default attributes for a variable product you can use WC_Product method get_default_attributes() this way:

<?php     global $product;    if( $product->is_type('variable') ){        $default_attributes = $product->get_default_attributes();        // Testing raw output        var_dump($default_attributes);    }?>

Now to find out which is the corresponding product variation for this "defaults" attributes, is a little more complicated:

<?php     global $product;    if( $product->is_type('variable') ){        $default_attributes = $product->get_default_attributes();        foreach($product->get_available_variations() as $variation_values ){            foreach($variation_values['attributes'] as $key => $attribute_value ){                $attribute_name = str_replace( 'attribute_', '', $key );                $default_value = $product->get_variation_default_attribute($attribute_name);                if( $default_value == $attribute_value ){                    $is_default_variation = true;                } else {                    $is_default_variation = false;                    break; // Stop this loop to start next main lopp                }            }            if( $is_default_variation ){                $variation_id = $variation_values['variation_id'];                break; // Stop the main loop            }        }        // Now we get the default variation data        if( $is_default_variation ){            // Raw output of available "default" variation details data            echo '<pre>'; print_r($variation_values); echo '</pre>';            // Get the "default" WC_Product_Variation object to use available methods            $default_variation = wc_get_product($variation_id);            // Get The active price            $price = $default_variation->get_price();         }    }?>

This is tested and works.


I found this question while looking for a simpler way to do it than I was, perhaps a built in WooCommerce function, but for now we still need to find it ourselves.

I did this a little bit differently, and by using microtime to test its performance on my hardware, it runs in about 1/2000 of the time. Here is my code:

function setDefaultVariation(): array {    global $product;    $all_variations = $product->get_available_variations();    $default_attributes = $product->get_default_attributes();    if (empty($default_attributes))        return $all_variations[0];    $default_variation_key = -1;    foreach ($all_variations as $variation) {        $default_variation_key++;        //Check if variation has more or less assigned attributes than the default.        if (getAssignedAttributeCount($variation['attributes']) !== count($default_attributes))            continue;        $is_default = 0; //This will count how many attributes match the default values        //We check each default attribute term and value to see if it matches the term-value pairs of the current variation. Some might have multiple pairs, so we use a counter to know if all are matched        foreach ($default_attributes as $default_term => $default_value) {            if($variation['attributes']['attribute_' . $default_term] !== $default_value) {                break; //A attribute value does not match so this one cant be default, break.            }else{                $is_default++;                if ($is_default === count($default_attributes) ) { //All default attributes matches this variation                    return $all_variations[$default_variation_key];                }            }        }    }    return $all_variations[0];//If this statement is reached, no default variation was found, so return key of first variation}function getAssignedAttributeCount($attributes): int {    $count = 0;    foreach ($attributes as $attribute) {        if ($attribute !== '')            $count++;    }    return $count;}

The code finds the default attributes for a product, then loops through each variation to check if the variation's attributes matches the default attributes.

It supports products that have multiple attributes, and also checks that the variation has the exact attributes by comparing the number of attributes, so for example (NULL is a where a default value for an attribute is not set):

Default|0|NULL|Variation 1:|0|2| -> The 0 matches, but the 2 does not, so this is not default!Variation 2:|0|NULL| -> This is the default

To achieve this, I added the getAssignedAttributeCount() function.

Also note that if no default variation is set, or no variation matching the default values is found, then the first variation is returned.