Ram
Ram

Reputation: 347

Empty cart before add to cart in WooCommerce

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.

Upvotes: 14

Views: 23808

Answers (2)

LoicTheAztec
LoicTheAztec

Reputation: 253773

Updated (with 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

Upvotes: 35

Waiseman
Waiseman

Reputation: 37

Go to your site database and look for table 'wp_woocommerce_sessions' and see if its 'session_id' column contains 0 value if so

  1. delete all these 0 entry records
  2. make 'session_id' Column as primary.
  3. make 'session_id' Column auto increment.

Upvotes: -1

Related Questions