Skip to content
Advertisement

Get all Product Variations based on one default attribute value in WooCommerce

Following Loic’s workflow here Can I get all the variations related to the product basing on one particular variation in default value.

Example: Get all variations with attribute_pa_sizes similar to the default value’s attribute_pa_sizes

echo $variation_values['attributes']['attribute_pa_sizes'] . ': ' . $price ;

Advertisement

Answer

This can be done with the following code (based on this answer):

<?php 
    global $product;

    $variation_ids = array();
    $targeted_attribute = 'pa_sizes';

    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 );
                if( $attribute_name == $targeted_attribute ){
                    $default_value = $product->get_variation_default_attribute($attribute_name);
                    if( $default_value == $attribute_value ){
                        // We set all related variation IDs in an array
                        $variation_ids[] = $variation_values['variation_id'];
                    }
                }
            }
        }

        if( count( $variation_ids ) > 0 ){
            // Iterating through each variation ID 
            foreach( $variation_ids as $variation_id ){
                // Get the "default" WC_Product_Variation object
                $variation = wc_get_product($variation_id);
                // Get variation attribute values
                $variation_attributte = $variation->get_variation_attributes();
                // Raw output variation attribute values
                echo '<pre>'; print_r($variation_attributte); echo '</pre>';
                // Get the active price
                $price = $variation->get_price();
                // Output price
                echo '<p>Price: ' . $price . '</p>';
            }
        }
    }
?>

Tested and works

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement