11

I am new to WooCommerce and I need to be able to only add one single product in the cart. I want to clear all products and add the current product to the cart when I click the "Add to cart" button.

How can I do that ?

Maxime
  • 8,645
  • 5
  • 50
  • 53
spsaravananct
  • 392
  • 2
  • 4
  • 17

2 Answers2

22

I have got an exact solution for this. Try following code.

add_filter( 'woocommerce_add_cart_item_data', 'wdm_empty_cart', 10,  3);

function wdm_empty_cart( $cart_item_data, $product_id, $variation_id ) 
{

    global $woocommerce;
    $woocommerce->cart->empty_cart();

    // Do nothing with the data and return
    return $cart_item_data;
}

The above filter is defined in class-wc-cart.php within function add_to_cart().
http://docs.woothemes.com/wc-apidocs/source-class-WC_Cart.html#774-905
Thus, when add to cart button is pressed, it empties the cart and then add the product.

Domain
  • 11,562
  • 3
  • 23
  • 44
  • Would it be helpful to lower the priority a bit, so that our filter to empty cart is run before anything else? – Erenor Paz Feb 08 '17 at 08:27
  • I tried so many things to fix this problem and this was the one that worked. Thank you, works perfectly now. – Dave Dec 11 '18 at 03:17
16

Try this,

//For removing all the items from the cart
global $woocommerce;
$woocommerce->cart->empty_cart();
$woocommerce->cart->add_to_cart($product_id,$qty);

class file is wp-content/plugins/woocommerce/classes/class-wc-cart.php

Hope its helps..

Jobin
  • 8,238
  • 1
  • 33
  • 52
  • Hey, where should i put this in class-wc-cart.php? – Manik Arora Oct 23 '15 at 16:40
  • 1
    You shouldn't be modifying the plugin files directly. They'll be overwritten whenever the user updates. – Howdy_McGee Mar 28 '18 at 20:29
  • 1
    @Howdy_McGee You don't need to modify core file I just added it for reference , you can add the global in your functions.php then do the task with an ajax call. – Jobin Mar 29 '18 at 05:12