Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete previous items from cart when user logs in again in WooCommerce

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?

like image 359
Alek_86 Avatar asked Jan 29 '23 00:01

Alek_86


2 Answers

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);
?>
like image 103
Aleksandar Jakovljevic Avatar answered Jan 30 '23 14:01

Aleksandar Jakovljevic


try this:

add_filter( 'woocommerce_persistent_cart_enabled', '__return_false' );

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

like image 21
Maksym Berezhnoy Avatar answered Jan 30 '23 14:01

Maksym Berezhnoy