Home > front end >  When a specific product is added to WooCommerce cart, empty cart THEN add product
When a specific product is added to WooCommerce cart, empty cart THEN add product

Time:07-08

This code currently works to clear cart before adding a product to cart.

// Empty cart when product is added to cart, so we can't have multiple products in cart
add_action( 'woocommerce_add_cart_item_data', function( $cart_item_data ) {
    wc_empty_cart();
    return $cart_item_data;
} );

However I'm having trouble with making it product specific.

I'd like it to function as - if product ID#1 is added to cart, empty cart then add product (at whatever quantity).

How can I determine via the woocommerce_add_cart_item_data hook which product is added to the cart?

CodePudding user response:

The woocommerce_add_cart_item_data hook contains 3 arguments versus 1, and since $product_id is the 2nd it can be used to answer your question:

function filter_woocommerce_add_cart_item_data( $cart_item_data, $product_id, $variation_id ) {
    // Get product ID
    $product_id = $variation_id > 0 ? $variation_id : $product_id;
        
    // When product ID is in array (multiple product IDs can be added, separated by a comma)
    if ( in_array( $product_id, array( 1, 32, 30, 817 ) ) ) {
        wc_empty_cart();
    }

    return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'filter_woocommerce_add_cart_item_data', 10, 3 );
  • Related