I am trying to pull out a list of product variations from a Woocommerce installation, with their attributes – something like this:
product id variationid name color size
5 1234 swimsuit blue 10
5 1235 swimsuit blue 12
5 1236 swimsuit blue 14
5 1237 swimsuit red 10
I can get the variation ID and the product ID, and the product name like this:
<?php
// Get the variations
$args = array( 'post_type' => 'product_variation');
$variationloop = new WP_Query( $args );
while ( $variationloop->have_posts() ) : $variationloop->the_post();
// get the parent of each variation
$parent = get_post($post->post_parent);
// is the parent product live?
if ($parent->post_status=="publish")
{
$parentid=$post->post_parent;
echo $parentid; // product
echo $id; // variation id
echo $parent->post_title; // product name
}
?>
What I can’t figure out though, is how Woocommerce links a variation to an attribute, such as size. If I do this:
$sizes = get_the_terms($parentid ,'pa_size');
foreach ( $sizes as $size ) {
echo $size->name;
}
then I can get all the sizes that product could be available in, but I can’t find how to retrieve the size associated with variation 1234 only.
Attributes are stored on wp_term_relationships.
Ex:
Product 91 has an attribute 48