Woocommerce Delete all products from cart and add

2019-05-07 23:20发布

Hi i am new to woocommerce my problem is need to add single product only on cart,have to clear all products and add current product to cart when i click add to cart button

2条回答
唯我独甜
2楼-- · 2019-05-07 23:49

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.

查看更多
Emotional °昔
3楼-- · 2019-05-07 23:53

Try this,

//For removing all the items from the cart
global $woocommerce;
$woocommerce->cart->empty_cart();
$woocommerce->cart->add_to_cart($product_id,$qty);

class file is wp-content/plugins/woocommerce/classes/class-wc-cart.php

Hope its helps..

查看更多
登录 后发表回答