WooCommerce:购物车中只有 1 个产品.如果添加一个则替换 [英] WooCommerce: Only 1 product in cart. Replace if one is added

查看:24
本文介绍了WooCommerce:购物车中只有 1 个产品.如果添加一个则替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 WooCommerce 还很陌生,所以我不知道回答我的问题有什么用,这就是我没有添加任何代码块的原因.

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.

我想让客户只将一种产品添加到购物车,如果他们添加另一种产品,购物车中的当前产品将被上一个产品替换.

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.

我需要更改代码还是可以使用插件或 WooCommerce 设置?

Do I need to make changes in the code or is it possible with a plugin or WooCommerce setting?

我期待有帮助的回复.

谢谢

推荐答案

/**
* 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 );

将此代码添加到您的主题 functions.php 文件中.

Add this code your theme functions.php file.

希望有用!!享受

这篇关于WooCommerce:购物车中只有 1 个产品.如果添加一个则替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆