Adding a Variable Product in WooCommerce Programatically

How do I make it a variable product and add variations? Are variations handled like attributes?

this code creates a product and adds an attribute(XL size) but i cannot make that attribute used as a variation, width a custom price(etc).

this is a function called via ajax

function createnewproduct(){
$new_post = array(
    'post_title' => "Custom Variable",
    'post_content' => 'Lorem ipsum dolor sit amet...',
    'post_status' => 'publish',
    'post_type' => 'product'
);

$skuu = randomsku('csm','custom',6);
$post_id = wp_insert_post($new_post);
update_post_meta($post_id, '_sku', $skuu );
update_post_meta( $post_id, '_price', "25" );

//made it variable but variations wont be added!
wp_set_object_terms ($post_id, 'variable', 'product_type');
wp_set_object_terms( $post_id, 'XL', 'pa_size' );
//everything works well but
//how do i make the "pa_size" attribure a variation?

update_post_meta( $post_id, '_visibility', 'search' );
update_post_meta( $post_id, '_stock_status', 'instock');

}

this function declares in woocommerce that the new product added is a variable product and adds a “size” attribute . The problem is how we tell woocommerce that “size” attribute is a variation.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Found the solution to make a product attribute, a variation.
Lets say we have:

wp_set_object_terms( $post_id, 'XL', 'pa_size' );

Above is a custom attribute (a size attribute). In order to make it a variation you need to do this:

$thedata = Array('pa_size'=>Array(
        'name'=>'pa_size',
        'value'=>'',
        'is_visible' => '1', 
        'is_variation' => '1',
        'is_taxonomy' => '1'
        ));
update_post_meta( $post_id,'_product_attributes',$thedata);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x