Only one currently added product into Woocommerce cart?

前端 未结 2 613
孤独总比滥情好
孤独总比滥情好 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条回答
  • 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

    0 讨论(0)
  • 2021-01-23 11:19

    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;
    }
    
    0 讨论(0)
提交回复
热议问题