在 WooCommerce 中添加到购物车之前清空购物车 [英] Empty cart before add to cart in WooCommerce

查看:89
本文介绍了在 WooCommerce 中添加到购物车之前清空购物车的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 WP Job manager 和 Woo Subscriptions.

I am using WP Job manager with Woo Subscriptions.

现在:

  1. 最初,我选择了一个包(Woo Subscription)
  2. 然后我添加了所有细节.
  3. 但没有提交.
  4. 回到网站,所以要再次购买,我需要选择一个包裹.所以我选择了套餐并填写了详细信息,然后去了付款套餐.
  5. 现在我的购物车中有两个包裹(即我第一次选择的和最近没有购买的包裹)
  6. 如何解决这个问题,以便最新选择的一项在购物车中,而较早的一项在选择最新一项后立即删除.

我试过了 Woocommerce 删除购物车中的所有产品并将当前产品添加到购物车,但没有帮助.

I tried this Woocommerce Delete all products from cart and add current product to cart but did not help.

推荐答案

更新 (有 2 个不同的替代方案):

您应该尝试以下操作:

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;
}

代码位于活动子主题(或主题)的 functions.php 文件中.测试并适用 ajax-add-to-cart 和普通的 add-to-cart ......

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 item
add_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) );
    }
}

代码位于活动子主题(或主题)的 function.php 文件中.经过测试并有效

这篇关于在 WooCommerce 中添加到购物车之前清空购物车的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆