Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Woocommerce product variations outside loop

I'm trying to list product variations and prices for each variation outside of woocommerce templates. Anyone can suggest how can I access that info?

I have tried to do something like this:

$tickets = new WC_Product( $product_id);
$variables = $tickets->get_available_variations();

But this doesnt work because it is outside of loop, it returns error.

Idealy I would like to get all variations like an array:

$vars = array(
 array('name' => 'My var name', 'price' => '123'),
 array('name' => 'My var name', 'price' => '123'),
);

Maybe even if this can be done on 'save_post' for every product to create new post_meta and save this for future use, which would then be available to get like:

$meta = get_post_meta( $product_id, '_my_variations' );

Any suggestion is welcome.

like image 987
Bobz Avatar asked Oct 18 '25 06:10

Bobz


2 Answers

To get product variations outside the loop, you need to create new instance of WC_Product_Variable class, here is an example:

$tickets = new WC_Product_Variable( $product_id);
$variables = $tickets->get_available_variations();

In this way you will have all needed info for the variations in $variables array.

like image 165
Rado Avatar answered Oct 22 '25 05:10

Rado


This the simplest solution to get product variables using product ID, outside of loop and woocommerce template

$args = array(
'post_type'     => 'product_variation',
'post_status'   => array( 'private', 'publish' ),
'numberposts'   => -1,
'orderby'       => 'menu_order',
'order'         => 'asc',
'post_parent'   => $product_id // $post->ID 
);
$variations = get_posts( $args ); 
echo "<pre>"; print_r($variations); echo "</pre>"; 
like image 30
user2014 Avatar answered Oct 22 '25 04:10

user2014