3
votes

I have WordPress version 4.9.5 with our own theme, and WooCommerce as online shop solution.

Imagine that some user logs in to the website and adds some items in shop cart. Then he exits from website, whether he closes web page or logs out. After some time (doesn't matter is he on the same computer or not), when same user visit website (as a guest, without login) and adds some items in shoping cart and goes to checkout, WordPress merges two carts (items from the past and currently added in cart). I need to remove old items and keep only new items.

Example: (cart contents when user is logged in)

  • Item 1
  • Item 2

(cart contents when user is guest/logged out)

  • Item 3
  • Item 4

(cart contents after logging in during checkout)

  • Item 1
  • Item 2
  • Item 3
  • Item 4

I need cart to keep only:

  • Item 3
  • Item 4

How should I do that?

3

3 Answers

5
votes

Combining Sedimu's answer and a piece of code from this link: https://gist.github.com/maxrice/7dc500cd07fa70e2fb5251293d22e485 solution to your problem might be this:

<?php
function clear_persistent_cart_after_login( $user_login, $user ) {
    $blog_id = get_current_blog_id();
    // persistent carts created in WC 3.1 and below
    if ( metadata_exists( 'user', $user->ID, '_woocommerce_persistent_cart' ) ) {
        delete_user_meta( $user->ID, '_woocommerce_persistent_cart' );
    }

    // persistent carts created in WC 3.2+
    if ( metadata_exists( 'user', $user->ID, '_woocommerce_persistent_cart_' . $blog_id ) ) {
        delete_user_meta( $user->ID, '_woocommerce_persistent_cart_' . $blog_id );
    }
}
add_action('wp_login', 'clear_persistent_cart_after_login', 10, 2);
?>
3
votes

try this:

add_filter( 'woocommerce_persistent_cart_enabled', '__return_false' );

I tested it and it was working for me. I hope it helps you!

0
votes
  1. Add the below code to the function file if you want to clear the cart when a login is detected.

    <?php
    function clear_cart_afer_login( $user_login, $user ) {
    //For removing all the items from the cart
    global $woocommerce;
    $woocommerce->cart->empty_cart();
    }
    add_action('wp_login', 'clear_cart_afer_login', 10, 2);
    ?>
    
  2. Use this link below if you want to set general expiration time for woocomerce cart expiration

https://www.tmdhosting.com/kb/question/how-to-set-cart-expiration-in-woocommerce/

Let me know if this helps and dont forget to mark it as answer.