How To Get Product Variations & Meta – WooCommerce

Advertisement

How handy it could be if we can add product variations? much more handy and if we can easily get and retrieve those variations right?, yeah absolutely 🙂

I’ve been digging for this for few hours, until I saw and remember something that Variation in WooCommerce uses and save as a new custom post-type, so once again the simplicity of WooCommerce come to its best.

Lets get started.


$args = array(
	'post_type'     => 'product_variation',
	'post_status'   => array( 'private', 'publish' ),
	'numberposts'   => -1,
	'orderby'       => 'menu_order',
	'order'         => 'asc',
	'post_parent'   => get_the_ID() // get parent post-ID
);
$variations = get_posts( $args );

foreach ( $variations as $variation ) {

	// get variation ID
	$variation_ID = $variation->ID;

	// get variations meta
	$product_variation = new WC_Product_Variation( $variation_ID );

	// get variation featured image
	$variation_image = $product_variation->get_image();

	// get variation price
	$variation_price = $product_variation->get_price_html();

	// to get variation meta, simply use get_post_meta() WP functions and you're done :)
	// ... do your thing here

}

Hope that helps, happy coding ^_^

Advertisement