2
votes

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 prevent this by removing the coupon if there is no 1362 product id in the cart with Woocommerce ?

I know we can restrict coupon to a product but i don't want this, i want my coupon to be applied to all products cart only if there is the product with id 1362 in this cart.

add_action( 'woocommerce_before_cart', 'bbloomer_apply_matched_coupons' );

function bbloomer_apply_matched_coupons() {
    global $woocommerce;
    $coupon_code = 'boxpersonnalisable'; 
    if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;
    foreach ( $woocommerce->cart->cart_contents as $key => $values ) {
    // this is your product ID
    $autocoupon = array( 1362 );
    if( in_array( $values['product_id'], $autocoupon ) ) {  
    add_filter('woocommerce_coupon_message','remove_msg_filter',10,3);
        $woocommerce->cart->add_discount( $coupon_code );
        wc_print_notices();
    }
    }
}

Thank you very much

1
sorry was thinking to add another code to remove the couponPlayzare

1 Answers

3
votes

Here is the way to make it work when:

  • adding a specific coupon code when a specific product is added to cart
  • removing a specific applied coupon code when a specific product is removed from cart
  • (in both cases you can display a custom notice)…

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