Only one currently added product into Woocommerce cart?

家住魔仙堡 提交于 2019-12-02 03:55:25

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!