简体   繁体   中英

Only one currently added product into Woocommerce cart?

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

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 ?

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

Code goes in function.php file of your active child theme (or active theme).

Tested and works in all Woocommerce versions since 2.6.x

This working perfecty on Woocommerce 3.3.X

add_filter( 'woocommerce_add_to_cart_validation', 
'bbloomer_only_one_in_cart', 99, 2 );

function bbloomer_only_one_in_cart( $passed, $added_product_id ) {

global $woocommerce;

// empty cart: new item will replace previous
$woocommerce->cart->empty_cart();

// display a message if you like
wc_add_notice( 'Product added to cart!', 'notice' );

return $passed;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM