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.

1
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);

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *