I am trying to create a Wordpress plugin that creates variable products programmatically, but the problem is, I would like to use attributes I have previously defined manually from the admin dashboard. I need to assign the attribute to the the product I'm creating.
Here is the code that I am using (not mine, I got it from this answer: Create programmatically a variable product and two new attributes in WooCommerce):
function addProduct(){
//Create main product
$product = new WC_Product_Variable();
//Create the attribute object
$attribute = new WC_Product_Attribute();
//pa_size tax id
$attribute->set_id( 0 ); // -> SET to 0
//pa_size slug
$attribute->set_name( 'Couleur' ); // -> removed 'pa_' prefix
//Set terms slugs
$attribute->set_options( array(
'Noir'
) );
$attribute->set_position( 0 );
//If enabled
$attribute->set_visible( 1 );
//If we are going to use attribute in order to generate variations
$attribute->set_variation( 1 );
$product->set_attributes(array($attribute));
//Save main product to get its id
$id = $product->save();
$variation = new WC_Product_Variation();
$variation->set_regular_price(10);
$variation->set_parent_id($id);
//Set attributes requires a key/value containing
// tax and term slug
$variation->set_attributes(array(
'Couleur' => 'Noir' // -> removed 'pa_' prefix
));
//Save variation, returns variation id
echo get_permalink ( $variation->save() );
// echo get_permalink( $id ); // -> returns a link to check the newly created product
}
The product is correctly created, but the code creates a new attribute and calls it "Couleur" instead of using my already defined "Couleur" attribute.
Thanks in advance.