创建具有两个变体的新产品并将所选产品添加到购物车
期望的结果: 表单在变体之间进行选择,并将相应的变体添加到购物车。
当前结果:无论选择哪个,都将第二个变体添加到购物车
注意:添加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 );
慕尼黑8549860