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

别来无恙 提交于 2020-01-06 03:02:46

问题


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.

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

I am looking forward to helpful replies.

Thanks


回答1:


/**
* 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.

Hope It's useful !! Enjoy



来源:https://stackoverflow.com/questions/37528781/woocommerce-only-1-product-in-cart-replace-if-one-is-added

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!