当用户再次登录 WooCommerce 时,从购物车中删除以前的项目

Ale*_*_86 4 php wordpress woocommerce

我有我们自己主题的 WordPress 4.9.5 版,以及 WooCommerce 作为在线商店解决方案。

想象一下,某个用户登录网站并在购物车中添加了一些商品。然后他退出网站,无论是关闭网页还是注销。一段时间后(他是否在同一台计算机上无关紧要),当同一用户访问网站(作为访客,无需登录)并在购物车中添加一些商品并进行结帐时,WordPress 合并了两个购物车(商品来自过去和当前添加到购物车中)。我需要删除旧项目并只保留新项目。

示例:(用户登录时的购物车内容)

  • 第 1 项
  • 第 2 项

(用户为访客/登出时的购物车内容)

  • 第 3 项
  • 第 4 项

(结帐时登录后的购物车内容)

  • 第 1 项
  • 第 2 项
  • 第 3 项
  • 第 4 项

我只需要购物车保留:

  • 第 3 项
  • 第 4 项

我该怎么做?

小智 6

尝试这个:

add_filter( 'woocommerce_persistent_cart_enabled', '__return_false' );
Run Code Online (Sandbox Code Playgroud)

我测试了它,它对我有用。我希望它能帮助你!


Ale*_*vic 5

结合 Sedimu 的答案和此链接中的一段代码:https ://gist.github.com/maxrice/7dc500cd07fa70e2fb5251293d22e485 解决您的问题可能是这样的:

<?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);
?>
Run Code Online (Sandbox Code Playgroud)