Empty cart before add to cart in WooCommerce

Ram picture Ram · Mar 20, 2018 · Viewed 10.2k times · Source

I am using WP Job manager with Woo Subscriptions.

Now:

  1. Initially, I selected a package(Woo Subscription)
  2. Then I added all the details.
  3. But did not submit it.
  4. Came back to the site, so to buy again I need to select a package. So I selected the package and filled in details and went to the payment package.
  5. Now in my cart both the packages are present (i.e the one I selected without buying first time and the recent one)
  6. How can this be fixed so the latest selected one is in the cart and earlier one deleted as soon as latest one selected.

I tried this Woocommerce Delete all products from cart and add current product to cart but did not help.

Answer

LoicTheAztec picture LoicTheAztec · Mar 20, 2018

Updated (2 different alternatives):

You should try the following:

add_filter( 'woocommerce_add_to_cart_validation', 'remove_cart_item_before_add_to_cart', 20, 3 );
function remove_cart_item_before_add_to_cart( $passed, $product_id, $quantity ) {
    if( ! WC()->cart->is_empty() )
        WC()->cart->empty_cart();
    return $passed;
}

Code goes in functions.php file of your active child theme (or theme). Tested and works with both ajax-add-to-cart and normal add-to-cart…


Or you can use this different one that will keep in cart the last added item:

// Keep only last cart item
add_action( 'woocommerce_before_calculate_totals', 'keep_only_last_cart_item', 30, 1 );
function keep_only_last_cart_item( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    $cart_items = $cart->get_cart();

    if( count( $cart_items ) > 1 ){
        $cart_item_keys = array_keys( $cart_items );
        $cart->remove_cart_item( reset($cart_item_keys) );
    }
}

Code goes in function.php file of your active child theme (or theme). Tested and works