Create programmatically a variable product and two new attributes in WooCommerce

Viewed 30406

I would like to programmatically create a variable product ("parent" product) with two new variante attributes - all that from a WordPress plugin (so no HTTP Request to an API).

These two variante attributes should also be created on the fly.

How can this be done ?

(with WooCommerce version 3)


Update : I have 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.

3 Answers

Sarakinos answer only worked with two small but important modifications.

  1. The $attribute->set_id() needs to be set to 0.
  2. The $attribute->set_name(); and $variation->set_attributes() do not need the pa_ prefix. The methods already handle the prefixes.

So a working code would be:

//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( 'size' ); // -> removed 'pa_' prefix

//Set terms slugs
$attribute->set_options( array(
    'blue',
    'grey'
) );

$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(
    'size' => 'blue' // -> 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

Keep in mind, the product will be bare bones, and will be named 'product'. You need to set those values in the $product before you save it with $id = $product->save();.

Related