No products in the cart.
Forum Replies Created
Viewing 1 post (of 1 total)
- AuthorPosts
-
March 27, 2018 at 5:00 am in reply to: Create programmatically a variable product and two new attributes in WooCommerce #10013
sarakinos
ParticipantYou can also achieve this using the new native functions for setting/getting data from postmeta.
Here is an example that works ( based on the default dummy products of Woocommerce 3)
//Create main product $product = new WC_Product_Variable(); //Create the attribute object $attribute = new WC_Product_Attribute(); //pa_size tax id $attribute->set_id( 1 ); //pa_size slug $attribute->set_name( 'pa_size' ); //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(5); $variation->set_parent_id($id); //Set attributes requires a key/value containing // tax and term slug $variation->set_attributes(array( 'pa_size' => 'blue' )); //Save variation, returns variation id $variation->save();
You can add things like weight, tax, sku etc using the native functions available from Woocommerce 3 and on like set_price, set_sku ect.
Wrap it within a function and you are good to go.
- AuthorPosts
Viewing 1 post (of 1 total)