1

I need a coupon to be applied automatically when a product selects a custom field in it ( a checkbox as custom field) .If that checkbox is ticked in that product then woo commerce coupon should be applied automatically on cart and checkout page also well..I have written a custom code for it and its working fine .But if the checkbox is not selected and customer comes to checkout page - there is a default apply coupon code input box , if the customer puts the same coupon and apply's the coupon gets applied .But it shouldn't. The coupon was created on the back-end .

The code is :

add_action( 'woocommerce_before_checkout_form', 'apply_matched_coupons');
function apply_matched_coupons() {
    $coupon_code = 'promo25';     
    if (WC()->cart->has_discount($coupon_code)) 
        return;
    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        // this is your product ID
        $autocoupon = array(968);
        if (in_array($cart_item['product_id'], $autocoupon)) {   
            if (isset($cart_item[WCPA_CART_ITEM_KEY])) {
                foreach ($cart_item[WCPA_CART_ITEM_KEY] as $field) {    
                    if ($field['name'] == 'carpet-steam1') {
                        WC()->cart->add_discount($coupon_code);
                        wc_print_notices();
                    } 
                }
            }
        }  
    }
}

When promo25 is applied on checkout page, the coupon should not be applied.

Robert
  • 7,394
  • 40
  • 45
  • 64
sarah
  • 11
  • 1

0 Answers0