Search code examples
phpwordpresswoocommercecartcoupon

Allow some WooCommerce coupons set to "individual use" to be applied together


We have "individual use" ticked for all our coupons to stop multiple coupons being used.

There is an exception where we need these "individual use" coupons to be usable for another specific coupon.

For example:

3 coupons in total: Welcome 10 - Individual use - 10% off Welcome 20 - Individual use - 20% off Welcome 30 - 30% off

Welcome 10 and Welcome 20 will fail the validation as it does currently however, either Welcome 10 or Welcome 20 can be used with Welcome 30.

So Welcome 30 would essentially override the validation for individual_use.

Is this possible?


Solution

  • Note that in WooCommerce code the coupon code to be used is the coupon slug (so no capitals and no white spaces).

    So I have tested the code below with 3 coupon codes Welcome10, Welcome20 and Welcome30, all 3 set with "individual use" option restriction (so coupon code slugs are welcome10, welcome20 and welcome30).

    The code that allows welcome30 coupon code to be used with welcome10 or welcome20:

    add_filter( 'woocommerce_apply_individual_use_coupon', 'filter_apply_individual_use_coupon', 10, 3 );
    function filter_apply_individual_use_coupon( $coupons_to_keep, $the_coupon, $applied_coupons ) {
        
        if ( $the_coupon->get_code() === 'welcome30' ) {
            foreach( $applied_coupons as $key => $coupon_code ) {
                if( in_array( $coupon_code, array('welcome10', 'welcome20') ) ) {
                    $coupons_to_keep[$key] = $applied_coupons[$key];
                }
            }
        } elseif ( in_array( $the_coupon->get_code(), array('welcome10', 'welcome20') ) ) {
            foreach( $applied_coupons as $key => $coupon_code ) {
                if( $coupon_code == 'welcome30' ) {
                    $coupons_to_keep[$key] = $applied_coupons[$key];
                }
            }
        }
        return $coupons_to_keep;
    }
    
    
    add_filter( 'woocommerce_apply_with_individual_use_coupon', 'filter_apply_with_individual_use_coupon', 10, 4 );
    function filter_apply_with_individual_use_coupon( $apply, $the_coupon, $applied_coupon, $applied_coupons ) {
        if ( $the_coupon->get_code() === 'welcome-30' && in_array( $applied_coupon->get_code(), array('welcome10', 'welcome20') ) ) {
            $apply = true;
        } elseif ( in_array( $the_coupon->get_code(), array('welcome10', 'welcome20') ) && $applied_coupon->get_code() === 'welcome30' ) {
            $apply = true;
        }
        return $apply;
    }
    

    Code goes in functions.php file of the active child theme (or active theme). Tested and works.