WooCommerce Delete all products from cart and add current product to cart

前端 未结 2 1033
面向向阳花
面向向阳花 2021-02-14 18:44

I am new to WooCommerce and I need to be able to only add one single product in the cart. I want to clear all products and add the current product to the cart when I click the \

2条回答
  •  梦毁少年i
    2021-02-14 19:03

    I have got an exact solution for this. Try following code.

    add_filter( 'woocommerce_add_cart_item_data', 'wdm_empty_cart', 10,  3);
    
    function wdm_empty_cart( $cart_item_data, $product_id, $variation_id ) 
    {
    
        global $woocommerce;
        $woocommerce->cart->empty_cart();
    
        // Do nothing with the data and return
        return $cart_item_data;
    }
    

    The above filter is defined in class-wc-cart.php within function add_to_cart().
    http://docs.woothemes.com/wc-apidocs/source-class-WC_Cart.html#774-905
    Thus, when add to cart button is pressed, it empties the cart and then add the product.

提交回复
热议问题