[英]WooCommerce check cart contents on add to cart
I only have one product to display, but I offer two options for it: A payment plan (handled through a subscription plugin) and a single payment. 我只有一种产品要显示,但是我提供了两种选择:付款计划(通过订阅插件处理)和单笔付款。 I have them displayed on my site as a grouped and both options have an "Add to Cart" Button.
我将它们分组显示在我的网站上,并且两个选项都有一个“添加到购物车”按钮。 I don't want either option to be in the cart at the same time as the other.
我不希望任何一个选项与另一个选项同时出现在购物车中。 What I would like to do is either,
我想做的就是
A) Empty the cart before each time the add to cart is clicked. A)每次单击添加到购物车之前,清空购物车。
or 要么
B) Check if the cart contains a product already (via productid), and remove the payment plan if the full pay is selected, or vice versa. B)检查购物车是否已包含商品(通过productid),如果选择了全额付款,则删除付款计划,反之亦然。 Here is something I've come up with for this option, but I'm a bit lost and it's not functioning quite right.
这是我为该选项准备的,但是我有点迷茫,并且运行不正常。
global $woocommerce;
if ($product_id = 66){
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $cart_item ) {
echo $cart_item_key;
if($cart_item['product_id'] == '69'){
//remove single product
$woocommerce->cart->remove_cart_item($cart_item_key);
}
}
}
elseif ($product_id = 69){
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $cart_item ) {
echo $cart_item_key;
if($cart_item['product_id'] == '66'){
//remove single product
$woocommerce->cart->remove_cart_item($cart_item_key);
}
}
}
I'm thinking of adding this to the add_to_cart method before the try/catch to throw any errors. 我正在考虑在try / catch引发任何错误之前将其添加到add_to_cart方法中。 Can anyone help me figure a better solution?
谁能帮我找到更好的解决方案?
Emptying the cart would be very easy 清空购物车非常容易
add_filter( 'woocommerce_add_to_cart_validation', 'so_31392001_empty_cart', 10, 3 );
function so_31392001_empty_cart( $valid, $product_id, $quantity ) {
WC()->cart->empty_cart();
return $valid;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.