Woocommerce购物车中当前仅添加一种产品? [英] Only one currently added product into Woocommerce cart?

查看:135
本文介绍了Woocommerce购物车中当前仅添加一种产品?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望Woocommerce只允许购物车中有1种产品。如果某件商品已经在购物车中,并且已添加另一件商品,则应删除前一个。

I would like Woocommerce to only allow 1 product in the cart. If a product is already in the cart and another one is added then it should remove the previous one.

我在网上找到了以下代码:

I found this code on net:

/**
 * When an item is added to the cart, remove other products
 */
function custom_maybe_empty_cart( $valid, $product_id, $quantity ) {

if( ! empty ( WC()->cart->get_cart() ) && $valid ){
    WC()->cart->empty_cart();
    wc_add_notice( 'Only allowed 1 item in cart, please remove previous 
item.', 'error' ); // here instead popup notice need to remove prevous added product
}

return $valid;

}
add_filter( 'woocommerce_add_to_cart_validation', 'custom_maybe_empty_cart', 
10, 3 );

但是,这似乎并没有达到我想要的效果。它需要自动删除购物车中之前添加的产品,并在购物车中添加最新添加的产品。有人可以给我提示在最新的woo 3.3.X中需要更新的类吗?

But it seems that is not working as I wanted. It need to autoremove previously added product in cart, and add latest added product in cart. Can someone to give me tip what need to update on class to work in latest woo 3.3.X ?

推荐答案

这是更紧凑,更实际的代码,因为不再需要 global $ woocommerce

This one is the more compact and actual code as global $woocommerce is not needed anymore:

add_filter( 'woocommerce_add_to_cart_validation', 'auto_empty_cart', 20, 3 );
function auto_empty_cart( $passed, $product_id, $quantity ) {
    if( WC()->cart->is_empty() ) return $passed; // Exit

    WC()->cart->empty_cart();
    return $passed;
}

代码包含在您活动的子主题的function.php文件中(或活动主题)。

经过测试,并且可以在2.6.x以后的所有Woocommerce版本中使用。

Tested and works in all Woocommerce versions since 2.6.x

这篇关于Woocommerce购物车中当前仅添加一种产品?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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