7

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.

  • 1
    What about $attr = get_post_meta($id, '_product_attributes', true); echo '<pre>'; print_r($attr); echo '</pre>'; ? – gmazzap Sep 13 '13 at 1:51
  • 2
    Dear G.M. I am sorry to have made you read all that: I have just realised that I am a world class numpty and was running my code on my test site, but looking at my live data in the MySQL database. So the IDs didn't match up. I am so sorry. You are 100% right that get_post_meta is the answer to my woes, I just needed to look in the right dratted database! – Victoria Sep 13 '13 at 8:02
  • 1
    Dear Victoria, you make me smile :) – gmazzap Sep 13 '13 at 9:00
  • 4
    I have to say, it really sucks this stackexchange attitude that WooCommerce is off-topic. It's a platform, used by tons of people who use Wordpress. The question is relevant. – Dave Hilditch Jun 26 '15 at 14:23
0

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

| improve this answer | |
  • 1
    They are also stored in a JSON string in wp_postmeta against the _product_attributes key. Presumably they duplicated for performance reasons. – Dave Hilditch Jun 26 '15 at 14:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.