WooCommerce: how to echo product variation?

2.7k Views Asked by At

I am printing a stock/inventory report from WooCommerce. How can I echo the products variations i.e. product color or size, etc?

$loop = new WP_Query( $args );

while ( $loop->have_posts() ) : $loop->the_post();

$product = new WC_Product_Variation( $loop->post->ID );
?>
<tr>
<td><?php echo $product->get_title(); ?></td>
<td><?php echo get_the_title( $loop->$product->get_attributes ); ?></td>
<td><?php echo $product->sku; ?></td>
<td><?php echo $product->stock; ?></td>
</tr>
<?php
endwhile;

I have tried the following but I get something like: Variation #49379

<?php echo get_the_title( $loop->get_post_meta( $thepostid, '_product_attributes', true ) ); ?>
2

There are 2 best solutions below

1
On

You can use: echo $product->get_available_variations();

If this is a single style template, make sure you add global $product; near the top.

0
On

If you have product-id then this will be the solution

$product = wc_get_product($productid);
$variations = $product->get_available_variations();

Now you may loop through this variation to print all variations.

Hopefully, this will resolve your issue.