我正在尝试使用此功能将产品添加到我的购物车:
WC()->cart->add_to_cart( $id, $quantity=1,$variation_id );
但是,它仅在购物车为空时才有效。如果购物车中已有产品,则不会添加新产品。出于测试目的,我正在使用这样的表单按钮:
<form name="addpro" method="post" action="">
<input type="submit" name="addcustomcarts" value="ADD TOO CART">
</form>
这是我将产品添加到购物车的代码:
add_action('init', 'customcart');
function customcart() {
if (isset($_POST["addcustomcarts"])) {
// global $woocommerce;
//Create main product
$product = new WC_Product_Variable();
$product->set_name("Tdwo");
//Create the attribute object
$attribute = new WC_Product_Attribute();
//pa_size tax id
$attribute->set_id( 0 ); // -> SET to 0
//pa_size slug
$attribute->set_name( 'size' ); // -> removed 'pa_' prefix
//Set terms slugs
$attribute->set_options( array(
'blue',
'grey'
) );
$attribute->set_position( 0 );
//If enabled
$attribute->set_visible( 1 );
//If we are going to use attribute in order to generate variations
$attribute->set_variation( 1 );
$product->set_attributes(array($attribute));
//Save main product to get its id
$id = $product->save();
$variation = new WC_Product_Variation();
$variation->set_regular_price(10);
$variation->set_parent_id($id);
//Set attributes requires a key/value containing
// tax and term slug
$variation->set_attributes(array(
'size' => 'blue' // -> removed 'pa_' prefix
));
//Save variation, returns variation id
$variation_id = $variation->save() ;
echo $variation_id;
// echo get_permalink( $id ); // -> returns a link to check the newly created product
WC()->cart->add_to_cart( $id, $quantity=1,$variation_id );
exit( wp_redirect( get_permalink( woocommerce_get_page_id( 'cart' ) ) ) );
}
}