我需要将产品更改为变量,添加新变体,并将产品添加到购物车......这是我到目前为止所拥有的。我只想让购物车显示变量名称......
//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,?,?);
两个问号 - 问题是我如何获得变量_id以及我应该在数组中添加什么?
答案 0 :(得分:3)
对,所以这比我最初想的要复杂一点......
变体就像一个产品,它有一个帖子,需要至少3个参数元,股票和价格。
所以我们走了......
//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));