WooCommerce: Only 1 product in cart. Replace if on

2019-07-25 06:40发布

问题:

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