创建新的产品变体并将选定的变体添加到购物车

创建具有两个变体的新产品并将所选产品添加到购物车


期望的结果: 表单在变体之间进行选择,并将相应的变体添加到购物车。


当前结果:无论选择哪个,都将第二个变体添加到购物车


注意:添加variation_id应该非常简单,但由于尚未创建变体 ID,我需要一种方法将表单中的变体术语与新分配的variation_id


<form name="new-prod" method="post" action="">

<input type="radio" name="attribute_pa_size" value="11oz" id="pa_size_v_11oz">

<input type="radio" name="attribute_pa_size" value="15oz" checked="checked" id="pa_size">

PHP:


$post_size = $_POST['attribute_pa_size'];

创建了多个变体:


第一个变体


$parent_id = $product_ID;

$variation = array(

'post_title'   => 'Product #' . $parent_id . ' Variation',

'post_content' => '',

'post_status'  => 'publish',

'post_parent'  => $parent_id,

'post_type'    => 'product_variation'

);

$variation_id = wp_insert_post( $variation );

update_post_meta( $variation_id, '_regular_price', 21.95 );

update_post_meta( $variation_id, '_price', 21.95 );

update_post_meta( $variation_id, 'attribute_' . $mythis->size_tax, '15oz' );

WC_Product_Variable::sync( $parent_id );

第二变体


$parent_id = $product_ID;

$variation = array(

'post_title'   => 'Product #' . $parent_id . ' Variation',

'post_content' => '',

'post_status'  => 'publish',

'post_parent'  => $parent_id,

'post_type'    => 'product_variation'

);

$variation_id = wp_insert_post( $variation );

update_post_meta( $variation_id, '_regular_price', 18.95 );

update_post_meta( $variation_id, '_price', 18.95 );

update_post_meta( $variation_id, 'attribute_' . $mythis->size_tax, '11oz' );

WC_Product_Variable::sync( $parent_id );

将变体添加到购物车


$quantity     = 1;

$variation    = $post_size;

$woocommerce->cart->add_to_cart( $product_ID, $quantity, $variation_id, $variation  );



慕尼黑的夜晚无繁华
浏览 74回答 1
1回答

慕尼黑8549860

$variation_id替换$elevenvariation_id了第一个变体的所有引用。然后用以下内容替换了“将变体添加到购物车”块,它从我的初始测试开始就成功了:&nbsp; $quantity&nbsp; &nbsp; &nbsp;= 1;&nbsp; $variation&nbsp; &nbsp; = $post_size;$answer = $_POST['attribute_pa_size'];&nbsp;&nbsp;if ($answer == "15oz") {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;$woocommerce->cart->add_to_cart( $product_ID, $quantity, $variation_id, $variation&nbsp; );&nbsp; &nbsp;}&nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; $woocommerce->cart->add_to_cart( $product_ID, $quantity, $elevenvariation_id, $variation&nbsp; );&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP