Get all product variations of a product given its ID in Woocommerce

I have a custom page where I’m trying to list every products in the store along with their variations.

Also, I’m trying to list the variations’ prices sorted by the product attribute with slug ‘size’

Read More

For testing, I’m trying to get the variations of a single product with the ID 381
My code yet is

    $handle=new WC_Product('381');
    $variations1=$handle->get_avaialable_variations();
    foreach ($variations1 as $key => $value) {
            echo '<option  value="'.$value['variation_id'].'">'.implode('/',$value['attributes']).'-'.$value['price_html'].'</option>';

    }

But the error I’m getting is

PHP Fatal error:  Call to undefined method WC_Product::get_avaialable_variations() 

I tried using

$handle=new WC_Product_Variable('381');

instead of

 $handle=new WC_Product('381'); 

But the error is the same.

Any help here?

Related posts

3 comments

  1. Try this code.

    $handle=new WC_Product_Variable('12');
    $variations1=$handle->get_children();
    foreach ($variations1 as $value) {
        $single_variation=new WC_Product_Variation($value);
        echo '<option  value="'.$value.'">'.implode(" / ", $single_variation->get_variation_attributes()).'-'.get_woocommerce_currency_symbol().$single_variation->price.'</option>';
    }
    

    Note: Use this $single_variation->get_price_html() but its outputs with html span tag which results in getting hidden in option tags.

    Tested the above code and the results are as follows.

    Let me know if that worked for you too.

    enter image description here

  2. You had a typo in your code – get_avaialable_variations

    It should be get_available_variations

  3. function get_variation_data_from_variation_id($item_id) {
    
        $_product = new WC_Product_Variation($item_id);
        $variation_data = $_product->get_variation_attributes(); // variation data in array
        $variation_detail = woocommerce_get_formatted_variation($variation_data, true);  // this will give all variation detail in one line
        // $variation_detail = woocommerce_get_formatted_variation( $variation_data, false);  // this will give all variation detail one by one
        return $variation_data; // $variation_detail will return string containing variation detail which can be used to print on website
        // return $variation_data; // $variation_data will return only the data which can be used to store variation data
    }
    

    I found this before on stackoverflow couldn’t remember the link (please edit if find the link to the answer with this method). it shows the variation data for output. the method takes variation id as perameter.

    output:

    enter image description here.

Comments are closed.