How does Woocommerce store variation attributes, and how can they be retrieved per-variation?

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:

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

Related posts

1 comment

  1. Attributes are stored on wp_term_relationships.

    Ex:

    +--------------+-------------------+-------------------+
    | object_id    | term_taxonomy_id  | term_taxonomy_id  |
    +--------------+-------------------+-------------------+
    | 91           | 48                | 0                 |
    +--------------+-------------------+-------------------+
    

    Product 91 has an attribute 48

Comments are closed.