I have this code to empty the cart before adding new item to the cart.
add_action( 'woocommerce_add_cart_item_data', 'woocommerce_clear_cart_url' );
function woocommerce_clear_cart_url() {
global $woocommerce;
$woocommerce->cart->empty_cart();
}
But I want to limit this function to product id 986 and 1146. I mean when ever the customer add product id 986 or 1146, empty the cart first!
please help me i am totally noob
Try the following which will empty cart before whenadding to cart product Ids 986
or **1146**
:
add_filter( 'woocommerce_add_to_cart_validation', 'custom_empty_cart', 10, 3 );
function custom_empty_cart( $passed, $product_id, $quantity ) {
if( ( ! WC()->cart->is_empty() ) && in_array( $product_id, [986, 1146] ) )
WC()->cart->empty_cart();
return $passed;
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.