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.
2
Answers
Thanks to Vincenzo Di Gaetano, the problem was solved.
Here's the working code:
WooCommerce allows you to use global attributes and product-level (local or custom) attributes.
Global attributes are available for all products. When you delete a term for that attribute, it will be removed for all products that use that attribute with that term. Conversely, when you add a new term it will be available for all other products.
While the product-level (local or custom) attribute is only defined for that product and will not be available for others.
You can find more detailed information here:
SOLUTION
Programmatically you will need to add the prefix
pa_
to each attribute slug.Also you are setting the id to zero:
$attribute->set_id( 0 );
but by doing this you are setting a product-level (and not global) attribute. You will need to change this line to:Instead of using this answer you should use this.
USEFUL LINK