85411

Allow only one product per product category in cart

Question:

On this <a href="https://stackoverflow.com/questions/42400501/restricting-cart-items-to-be-from-the-same-product-category" rel="nofollow"><strong>Question / Answer</strong></a> I have found the PHP code about how to just add one product per category in cart in Woocommerce.

The code works just fine, but I want to add the latest added product to cart and if there is already a product of that category in the cart, I want to have the oldest deleted.

add_filter( 'woocommerce_add_to_cart_validation', 'custom_checking_product_added_to_cart', 10, 3 ); function custom_checking_product_added_to_cart( $passed, $product_id, $quantity) { // HERE Type your alert displayed message // $message = __( 'BLA BLA YOUR MESSAGE.', 'woocommerce' ); $product_cats_object = get_the_terms( $product_id, 'product_cat' ); foreach($product_cats_object as $obj_prod_cat){ $product_cats[] = $obj_prod_cat->slug; } foreach (WC()->cart->get_cart() as $cart_item ){ if( has_term( $product_cats, 'product_cat', $cart_item['product_id'] )) { $passed = false; wc_add_notice( $message, 'error' ); break; } } return $passed; }

It is a piece of code that comes from <a href="https://stackoverflow.com/users/3730754/loictheaztec" rel="nofollow"><strong>LoicTheAztec</strong> </a>. It works fine but I need an extra option...

In my Woocommerce there are 5 different categories, there is just place in the cart for one item per category. The latest added item should stay, the item of the same category that is already in cart must be removed from cart. Does someone of you has a solution?

Many thanks!

Answer1:

Here is your peace of code that will remove a cart item which product category match with the current product category.

add_filter( 'woocommerce_add_to_cart_validation', 'custom_checking_product_added_to_cart', 10, 3 ); function custom_checking_product_added_to_cart( $passed, $product_id, $quantity) { // Getting the product categories slugs in an array for the current product $product_cats_object = get_the_terms( $product_id, 'product_cat' ); foreach($product_cats_object as $obj_prod_cat) $product_cats[] = $obj_prod_cat->slug; // Iterating through each cart item foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item ){ // When the product category of the current product match with a cart item if( has_term( $product_cats, 'product_cat', $cart_item['product_id'] )) { // Removing the cart item WC()->cart->remove_cart_item($cart_item_key); // Displaying a message wc_add_notice( 'Only one product from a category is allowed in cart', 'notice' ); // We stop the loop break; } } return $passed; }

<em>This code goes in function.php file of your active child theme (or theme) or also in any plugin file.</em>

This code is tested and works for WooCommerce version 2.6+ and 3.0+

Recommend

  • How to run an R script and show a plot?
  • Batch script file name
  • woocommerce payment methods
  • Get the selected product variation ID in WooCommerce variable products single pages
  • invalid value in “less” when comparing np.nan in an array
  • Adding to Grid Selection for grid.php file
  • Dictionary with array of different types as value in Python
  • Multiple values for an AND/OR statement
  • Drupal: create a node with employee working hours
  • Hide background image using Media Queries
  • RegEx replacing IMG src attributes
  • Trying to total columns for relation datasource
  • WooCommerce - related products by tags and categories
  • Why is it still possible to insert a foreign key that doesn't exist?
  • LINQ join with filter criteria
  • Quick Question About Get and Set
  • MeeGo Handset Emulator not starting on Windows 7
  • C++ friend class std::vector
  • Knockout custom binding handler
  • Using $compile in a directive triggers AngularJS infinite digest error
  • How to make Twilio api Post request with the help of AFNetworking?
  • Unable to send e-mail through Java
  • didUpdatePushCredentials not get called
  • UIAlertController button function not working
  • SetWindowsHookEx does not react on media keys
  • Element.tagName for python not working
  • Graphics.CopyFromScreen [Web application] + The handle is invalid
  • How solve “Qt: Untested Windows version 10.0 detected!”
  • Install PHP intl extension on MacOS
  • Retrieve list of sent friend requests from friend_request FQL table
  • Functions in global context
  • NHibernate Validation Localization with S#arp Architecture
  • FileReader+canvas image loading problem
  • How can I send an e-mail from a vbs script
  • Accessing IRQ description array within a module and displaying action names
  • Compare two NSDates in iPhone
  • How do I configure my settings file to work with unit tests?
  • Getting Messege Twice Using IMvxMessenger
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • Binding checkboxes to object values in AngularJs