Creating Product Variations and Attributes - jasonknight/woocommerce-json-api GitHub Wiki

Product Attributes, when not a taxonomy, are saved to the meta table in the form of attribute_yournamehere. The way that the api handles meta attributes is with a map of names to database keys.

<?php
'tax_status'        => array(
   'name' => '_tax_status',           
   'type' => 'string',
   'values' => array(
    'taxable',
    'shipping',
    'none',
   ),
   'default' => 'none',
   'sizehint' => 1,
 ),

The above is the map for the tax_status attribute. Attributes like this are pretty fixed, they are almost always present, and are system defined. But custom attributes are stored the same way, but are user defined, so The API has no way of knowing about them.

The API comes with the ability for you to tell it about your own custom attributes in each request. Basically, by passing in a collection of maps. Say you create an attribute called Size, and it accepts Small, Medium, and Large.

You would create a normal set_products, or get_products request, and add to the request object something like this:

<?php
'model_filters' => array(
'WCAPI_product_meta_attributes_table' => array(
  // it can be size, size_attribute, my_size, any name you want.
  // this is the name that will be returned to you
  'size_attribute' => array(
   'name' => 'attribute_size', // this is non negotiable, has to be format attribute_yourattr          
   'type' => 'string', 
   'values' => array(
    'small',
    'medium',
    'large',
   ),
   'sizehint' => 2
 ),
)
)// end of model_filters array

Creating the variation

Ideally, you can create the variation in one go, but it's still a good idea to do it in these steps:

  • Create a product using set_products with a product_type of variable, and the attributes you would like to creat. The id of the new product will be returned to you,
  • Copy the returned product to a new object, and unset the id
  • Change the SKU and Price fields of the copied product
  • Set the parent_id of the copied product to the id of the just created product.
  • Set the type attribute to product_variation note, there is a differenve between type and product_type, this is because WooCommerce maintains a difference. product and product_varation are post types in WP Parlance, and variable simple and grouped etc are taxonomies. Because they are important to the functioning of a product, they are considered attributes by the API, but the backend handles them quietly as a taxonomy.
  • add any attribute filters to the request
  • Call set_products with the variations as the payload, it will create them in turn, and return them with ids, if you passed a custom attribute filter, those should be set as well.

Because the saving of Associations takes place after the saving of the main model, this should work as one set_products request.