Get changes in Woocommerce products outside the loop
I am trying to list product variations and prices for each option outside of woocommerce templates. Can anyone suggest how I can access this information?
I tried to do something like this:
$tickets = new WC_Product( $product_id);
$variables = $tickets->get_available_variations();
But it doesn't work because it's outside the loop, it returns an error.
Idealy I would like to get all options as an array:
$vars = array(
array('name' => 'My var name', 'price' => '123'),
array('name' => 'My var name', 'price' => '123'),
);
Maybe even if it could be done for a "save_post" for each product to create a new post_meta and save it for future use, which will then be available:
$meta = get_post_meta( $product_id, '_my_variations' );
Any suggestion is greatly appreciated.
source to share
To get product variations outside of the loop, you need to create a new instance of the WC_Product_Variable class, here's an example:
$tickets = new WC_Product_Variable( $product_id);
$variables = $tickets->get_available_variations();
This way, you will have all the information you need for the variations in the $ variable array.
source to share
This is the simplest solution to get product variables using product id, outside of loop template and woocommerce
$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>";
source to share