Need Woocommerce to only allow 1 product in the cart. If a product is already in the cart and another 1 is added then it should remove the previous 1

Swof picture Swof · Jan 26, 2014 · Viewed 35.8k times · Source

I think this code should work but not exactly sure where to place it. Everywhere I have tried has failed so far...

add_action('init', 'woocommerce_clear_cart');

function woocommerce_clear_cart() {
global $woocommerce, $post, $wpdb;

$url = explode('/', 'http://'.$_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
$slug=$url[4];
$postid = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_status='publish' AND post_name = '$slug'");

    if ($postid){
        if ($postid == PRODUCTID1 || $postid == PRODUCTID2){
        $woocommerce->cart->empty_cart();
        }
    }

}

Answer

fornyhucker picture fornyhucker · Mar 25, 2014

Unfortunately there is no 'action' hook before WooCommerce adds an item to the cart. But they have a 'filter' hook before adding to cart. That is how I use it:

add_filter( 'woocommerce_add_cart_item_data', 'woo_custom_add_to_cart' );

function woo_custom_add_to_cart( $cart_item_data ) {

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

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