Reputation: 159
I need to change a product to variable, add a new variation, and add the product to the cart...this is what I have so far. I just want the cart to show the variable name...
//set the product to variable
wp_set_object_terms($product_id, 'variable', 'product_type');
//make a variation
$thedata = Array('_course_calendar'=>Array(
'name'=>'_course_calendar',
'value'=>'',
'is_visible' => '1',
'is_variation' => '1',
'is_taxonomy' => '1'
));
update_post_meta($product_id,'_product_attributes',$thedata);
//product_id,quantity,variation id,array
$woocommerce->cart->add_to_cart($product_id,1,?,?);
The two question marks - the problem is how do I get the variation_id and what should I put in the array?
Upvotes: 3
Views: 1267
Reputation: 159
Right so this was a bit more complex than I first thought..
A variation is like a product, it has a post and needs at least 3 parameters for meta, stock and price.
So here we go...
//set the product to variable
wp_set_object_terms($product_id, 'variable', 'product_type');
//make an attribute and set it to variation, here the course calendar
//is simply the name of the var. What appears in the cart is the 'name'
//attribute so name it appropriately
$thedata = Array('course_calendar'=>Array(
'name'=>'details',
'value'=>'',
'is_visible' => '1',
'is_variation' => '1',
'is_taxonomy' => '1'
));
update_post_meta($product_id,'_product_attributes',$thedata);
//check the variation doesn't already exist if it does re-use it
$result = $wpdb->get_row("SELECT ID FROM {$wpdb->prefix}posts WHERE post_parent = $product_id", 'ARRAY_A');
if($result)
$id = $result["ID"];
//create the post variation if required
if(!$result)
{
$post = array(
'post_content' => "", // The full text of the post.
'post_name' => "product-".$product_id."-variation",
'post_title' => "variation added by <whatever> plugin", // The title of your post.
'post_status' => 'publish', // Default 'draft'.
'post_type' => "product_variation", // Default 'post'.
'post_author' => 100,
'ping_status' => 'open',
'post_parent' => $product_id, // Sets the parent of the new post, if any. Default 0.
'menu_order' => 0,
'post_date' => date("Y-m-d H:i:s"),
'post_date_gmt' => date("Y-m-d H:i:s"),
);
$id = wp_insert_post($post);
}
//set the stock/price meta, in my case a virtual product so no stock
//req'd, the 4th true param ensures it is unique so only set once
add_post_meta($id, "_virtual", "yes", true);
add_post_meta($id, "_price", 0, true);
//finally insert your new product with the variation id and
//a description which will appear in the cart etc...
$woocommerce->cart->add_to_cart($product_id,1,$id,Array('course_calendar'=>$product_desc));
Upvotes: 3