1
votes

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.

1
Perhaps a negative fee instead would be a better choice?uu01

1 Answers

1
votes

Code contains

function my_coupon_is_valid( $valid, $coupon ) {
    $coupon_code = 'promo25';

    //if checkbox is checked
    if( $coupon_code != 'promo25' && checkbox... ) ){
        $valid = false;
    }
    return $valid;
}
add_filter( 'woocommerce_coupon_is_valid', 'my_coupon_is_valid', 10, 2);

function coupon_error( $err, $err_code, $coupon ) {
    $coupon_code = 'promo25';

    // https://docs.woocommerce.com/wc-apidocs/source-class-WC_Coupon.html#947    
    if( $coupon_code == $coupon->get_code() && intval($err_code) === WC_COUPON::E_WC_COUPON_INVALID_FILTERED ) ) {
        $err = __( "Coupon $coupon_code don't work", "woocommerce" );
    }
    return $err;
}
add_filter('woocommerce_coupon_error', 'my_coupon_error', 10, 3);