wordpress WooCommerce 从购物车中删除所有产品并将当前产品添加到购物车
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21181911/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WooCommerce Delete all products from cart and add current product to cart
提问by spsaravananct
I am new to WooCommerce and I need to be able to only add one single product in the cart. I want to clear all products and add the current product to the cart when I click the "Add to cart" button.
我是 WooCommerce 的新手,我只需要在购物车中添加一个产品。当我单击“添加到购物车”按钮时,我想清除所有产品并将当前产品添加到购物车。
How can I do that ?
我怎样才能做到这一点 ?
回答by Jobin Jose
Try this,
尝试这个,
//For removing all the items from the cart
global $woocommerce;
$woocommerce->cart->empty_cart();
$woocommerce->cart->add_to_cart($product_id,$qty);
class file is wp-content/plugins/woocommerce/classes/class-wc-cart.php
类文件是 wp-content/plugins/woocommerce/classes/class-wc-cart.php
Hope its helps..
希望它有帮助..
回答by WisdmLabs
I have got an exact solution for this. Try following code.
我有一个确切的解决方案。尝试以下代码。
add_filter( 'woocommerce_add_cart_item_data', 'wdm_empty_cart', 10, 3);
function wdm_empty_cart( $cart_item_data, $product_id, $variation_id )
{
global $woocommerce;
$woocommerce->cart->empty_cart();
// Do nothing with the data and return
return $cart_item_data;
}
The above filter is defined in class-wc-cart.php within function add_to_cart().
http://docs.woothemes.com/wc-apidocs/source-class-WC_Cart.html#774-905
Thus, when add to cart button is pressed, it empties the cart and then add the product.
上述过滤器在 class-wc-cart.php 中的 add_to_cart() 函数中定义。
http://docs.woothemes.com/wc-apidocs/source-class-WC_Cart.html#774-905
因此,当按下添加到购物车按钮时,它会清空购物车然后添加产品。