Only one currently added product into Woocommerce cart?

前端 未结 2 617
孤独总比滥情好
孤独总比滥情好 2021-01-23 10:47

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 foun

2条回答
  •  猫巷女王i
    2021-01-23 11:19

    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

提交回复
热议问题