1

In WooCommerce, I am trying to get all the values of a variable product independently of each other.

For example:
I have the attribute size. Size has three values: size S, size M and size L.
If the product has all the options for size, I want to see the product three times in my output:

  • one time with size S,
  • one time with size M
  • and one time with size L.

With the following code I see which variations I have. Further i did not come unfortunately.

private function readOptions($product) {
    $variations = $product->get_children();
    foreach ($variations as $variation) {
        $single_variation=new WC_Product_Variation($variation);
        $this->doLog(print_r($single_variation->get_variation_attributes(), true));
    }              
}

Does anyone have any idea how to do this?

Thanks.

0

1 Answer 1

1

I got your function code here (well commented):

private function readOptions($product) {

    // Get all attributes & values set in the product (product variations)
    $variation_attributes = $product->get_variation_attributes();

    // iterating through each attribute
    foreach ($variation_attributes as $attribute_slug => $attribute_slug_values){

        // Getting the attribute object (the taxonomy object)
        $attribute_obj = get_taxonomy( $attribute_slug ); // Attribute name: $attribute_obj->label

        // Iterating through each attribute values set in the product
        foreach($attribute_slug_values as $attribute_slug_value){

            // Getting the object of the term value (and the name: $attr_value_obj->name)
            $attr_value_obj = get_term_by( 'slug', $attribute_slug_value, $attribute_slug );

            // Output the names of the product, the attribute and the value
            echo '<p>Product "'.$product->get_title().'" has attribute "'.$attribute_obj->label.'" with value "'.$attr_value_obj->name.'"</p>';
        }
    }          
}

You will get exactly what you are expecting.

Here the output is just an example, but you get for each attribute and values set in the product:
The product + an attribute + a value (for all attribute values set in it).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.