Skip to content
Blog Careers Google Partner 12+ Years · 5000+ Projects
Best Website design company in India January 18, 2021 2 min read

Clear cart data before adding new

How to clear cart data before adding new item to the cart ?

Solution:

  1. Login to your wordpress backend.
  2. Go to apperance > Theme Editor > functions.php
  3. Add the following code/* Clear cart data before adding new */
    // before addto cart, only allow 1 item in a cart
    add_filter( ‘woocommerce_add_to_cart_validation’, ‘woo_custom_add_to_cart_before’ );function woo_custom_add_to_cart_before( $cart_item_data ) {global $woocommerce;
    $woocommerce->cart->empty_cart();// Do nothing with the data and return
    return true;
    } 
  4. Save it . It works fine with all versions of WordPress and woo-commerce plugin.

 

 

What this code does

The snippet empties the WooCommerce cart every time a customer clicks Add to cart. As a result, the cart can hold only one product at a time, and the newest choice replaces the old one. The filter woocommerce_add_to_cart_validation runs just before an item goes in, so the old item leaves first.

When to clear cart data before adding new items

This behaviour suits stores where a customer should buy one thing per order. For example, it fits subscription plans, course enrolments, event tickets, donation amounts and single service bookings. However, it is the wrong choice for a normal shop, because customers expect to collect several products before they pay.

Points to check before you use it

  • Add the code to a child theme or a code snippets plugin, because a theme update overwrites the parent theme’s functions.php. WordPress explains child themes in its developer handbook.
  • Take a backup first, since one typing mistake in functions.php can stop the site from loading.
  • Tell customers what happens, for example with a line near the button, so a replaced item does not surprise them.
  • Test with simple and variable products, and also with quantities above one.

Need a store set up this way? See our WooCommerce development services and our custom WordPress development.

See also: Redirect to custom url after woocommerce checkout and How do I create custom WooCommerce shop page?.

Keep Reading

Related Articles

View All Articles