Empty cart before add to cart in WooCommerce
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 itemadd_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
Go to your site database and look for table 'wp_woocommerce_sessions' and see if its 'session_id' column contains 0 value if so
- delete all these 0 entry records
- make 'session_id' Column as primary.
- make 'session_id' Column auto increment.