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:

Read More
$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.

Related posts

Leave a Reply

2 comments

  1. 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.

  2. 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>";