I have created a variable product ("parent" product) in Woocommerce version 3+. From a Wordpress plugin, I would like to programmatically create the product variations ("children" product) with new attribute values.
The variation attributes are already set in Woocommerce.
So every time one variation is created, the new attribute's values should be created programmatically too and set in the parent Variable product.
How can this be done? is it possible?
Update : I had written more lines of codes on this that I wished, and tried many things to solve it, using woocommerce objects, and added missing data about terms, termmeta, the relationship from term with post, in the database using the wordpress database object - but nothing has sufficed to make it work. And I couldn't pin-point where I went wrong - that is why I couldn't provide a narrower problem - things for which stackoverflow is more made for.
Expanding on LoicTheAztec's answer, you can check if the attribute combination exists with the following modification to his code.
Example usage
If you want to generate products for testing in WooCommerce, you can use WooCommerce Smooth Generator, made by WooCommerce itself.
https://github.com/woocommerce/wc-smooth-generator
Example:
Src: https://github.com/woocommerce/wc-smooth-generator/blob/master/includes/Generator/Product.php
If you want to create products programatically, you can Product class with your needs.
From a defined variable product ID You will find bellow, a custom function that will add (create) a Product variation. The variable parent product needs to have set for it the needed attributes.
You will need to provide some information as:
This data has to be stored in a formatted multi dimensional array (see an example at the end).
This function will check if the attributes values (term name) already exist and if not: - it create it for the product attribute - set it in the parent variable product.
The custom function code:
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Usage (example with 2 attributes):
Tested and works.
You will get this in backend:
And it will work perfectly in front end.
I'm just going to throw this out there, since i couldn't get any of the above examples working. Don't ask me why as other people seem to have success. So, i took the minimalist approach and tried to figure out the bare essentials for a product attribute + variation (by creating it manually in wp and looking at the db) and came up with this.
This is not using global product attributes, but article specific ones. Hope it helps someone as i was about ready to tear my hair out before i got it working.
You might run into a problem here if the the taxonomy of the product is not registered beforehand somewhere else. If you want to make sure the taxonomy exists, you could add a conditional to LoicTheAztec's answer.
Something like this.