I am applying automatically a coupon when there is a product id 1362 in the cart, but when someone adds another product and delete the 1362 the coupon stays applied, how to prev
Here is the way to make it work when:
The code:
add_action( 'woocommerce_before_calculate_totals', 'auto_add_remove_coupon' );
function auto_add_remove_coupon( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$coupon_code = 'boxpersonnalisable';
$targeted_product_ids = array( 1362 );
$found = false;
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item ){
if( in_array( $cart_item['product_id'], $targeted_product_ids ) ){
$found = true;
break;
}
}
if ( ! $cart->has_discount( $coupon_code ) && $found ) {
$cart->add_discount( $coupon_code );
wc_clear_notices();
wc_add_notice( __("Your custom notice - coupon added (optional)","woocommerce"), 'notice');
} elseif ( $cart->has_discount( $coupon_code ) && ! $found ) {
$cart->remove_coupon( $coupon_code );
wc_clear_notices();
wc_add_notice( __("Your custom notice - coupon removed (optional)","woocommerce"), 'notice');
}
}
Code goes in function.php file of your active child theme (or active theme). Tested and works