当用户登录问题时,WooCommerce 来宾购物车项目与项目合并

WooCommerce guest cart items merged with items when user logs in issue

在 WooCommerce 中,我设置了一个具有 4 个变体的可变产品,并选中了“单独销售”复选框,因此只能将其中 1 个产品添加到购物车。展望未来,我将此产品的 4 个变体称为 'Packages'。

当 4 个包裹中的 1 个被添加到购物车时,我还使用此代码片段清空购物车:

add_filter( 'woocommerce_add_to_cart_validation', 'custom_empty_cart', 10, 3 );
function custom_empty_cart( $passed, $product_id, $quantity ) {
    if( ( ! WC()->cart->is_empty() ) && in_array( $product_id, [7193, 7194, 7195, 7196] ) )
        WC()->cart->empty_cart();

    return $passed;
}

基本上,添加到购物车的包裹不能超过 1 个,这正是我想要的。

但是,问题来了:

1. 用户注销了一个包裹留在购物车中的帐户

2. 然后用户将 4 个包裹中的 1 个作为客人添加到购物车

3. 然后用户重新登录帐户

4. 2 个包裹出现在购物车中:一个在注销前留在购物车中,另一个在重新登录前作为客人添加到购物车

有什么办法可以避免这种情况吗?只有在注销时添加到购物车的最新包裹才会出现在购物车中。

要避免此问题,请另外使用以下代码:

add_action( 'woocommerce_before_calculate_totals', 'keep_last_defined_package_in_cart', 20, 1 );
function keep_last_defined_package_in_cart( $cart ){
    if ( is_admin() && ! defined('DOING_AJAX' ) )
        return;
    
    $targeted_ids  = array( 7193, 7194, 7195, 7196 );
    $cart_items    = $cart->get_cart();
    $targeted_keys = array();

    if ( count( $cart_items ) > 1 ) {
        foreach ( $cart_items as $item_key => $item ) {
            if ( array_intersect( $targeted_ids, array($item['product_id'], $item['variation_id']) ) ) {
                $targeted_keys[] = $item_key;
            }
        }
        
        // Remove first related item when more than one
        if ( count( $targeted_keys ) > 1 ) {
            $cart->remove_cart_item( reset($targeted_keys) ); 
        }
    }
}

代码进入活动子主题(或活动主题)的 functions.php 文件。应该可以。