简体   繁体   English

WooCommerce:购物车中只有1件商品。 如果添加一个,请替换

[英]WooCommerce: Only 1 product in cart. Replace if one is added

I am fairly new to WooCommerce so I dont know what could be of use to answer my question, this is why I have not added any codeblocks. 我对WooCommerce相当新,所以我不知道什么可以用来回答我的问题,这就是为什么我没有添加任何代码块。

I would like to let customers only add one product to the cart and if they add another product the current product in cart is replaced by the last one. 我想让客户只将一个产品添加到购物车中,如果他们添加了另一个产品,购物车中的当前产品将被最后一个产品替换。

Do I need to make changes in the code or is it possible with a plugin or WooCommerce setting? 我是否需要在代码中进行更改,还是可以使用插件或WooCommerce设置?

I am looking forward to helpful replies. 我期待着有用的回复。

Thanks 谢谢

/**
* When an item is added to the cart, remove other products
*/
function custom_maybe_empty_cart( $valid, $product_id, $quantity ) {
  if( ! empty ( WC()->cart->get_cart() ) && $valid ){
           WC()->cart->empty_cart();
  wc_add_notice( 'Only allowed 1 item in cart.', 'error' );
   }
   return $valid;
  }
  add_filter( 'woocommerce_add_to_cart_validation', 'custom_maybe_empty_cart', 10, 3 );

Add this code your theme functions.php file. 添加此代码您的主题functions.php文件。

Hope It's useful !! 希望它有用!! Enjoy 请享用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 目前只有一款产品加入Woocommerce购物车? - Only one currently added product into Woocommerce cart? Woocommerce。 如果产品不在购物车中,请从购物车中删除其他产品。 不工作 - Woocommerce. if product is not in cart, remove additional product from cart. not working 当产品添加到 WooCommerce 中的购物车时,如何只运行一次脚本? - How to run script only once when a product added to the cart in WooCommerce? 迷你购物车中的空购物车按钮。 woocommerce - Empty Cart button in Mini Cart. woocommerce 如果在 Woocommerce 中添加了相同的产品,则删除购物车中的产品 - Delete the product in the cart, if the same product added in Woocommerce 在 Woocommerce 中一次只允许购物车中的一个产品类别 - Allow only one product category in cart at once in Woocommerce 在Woocommerce中仅允许更新一个商品类别的购物车商品数量 - Allow cart item quantity update for only one product category in Woocommerce Woocommerce:如何在购物车中只允许一种产品类型? - Woocommerce: How to allow only one product type in a cart? Woocommerce 中定义的产品类别中只允许购物车中的一件商品 - Allow only one item in cart from defined product categories in Woocommerce Woocommerce - 从购物车中仅删除一件产品 - Woocommerce - Remove Only one Unit of a product from cart
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM