phpwordpresswoocommercecartcoupon

Auto apply a predefined coupon code for any imputted 5 character coupon code in WooCommerce


I’m trying to configure WooCommerce to apply a predefined discount whenever a user enters any 5-character code in the coupon field. The goal is to:

Allow any 5-character code (no specific content required). Automatically apply a set discount whenever a 5-character code is entered.

I’ve attempted to intercept the coupon input and replace it with a predefined code in functions.php, but it’s not working as expected.

Objective: Allow any 5-character code to trigger a predefined discount. Expected Outcome: Entering any 5-character code in the coupon field should automatically apply the discount.

Here is my code attempt (added to my theme functions.php file):

add_action('woocommerce_applied_coupon', 'apply_any_5char_coupon_code', 10, 1);

function apply_any_5char_coupon_code($coupon_code) {
    // Only proceed if the entered code is exactly 5 characters
    if (strlen($coupon_code) == 5) {
        // Replace entered code with a predefined coupon code, e.g., "PREDEFINED50"
        $predefined_coupon_code = 'PREDEFINED50';
        
        // Remove the entered coupon and apply the predefined one
        WC()->cart->remove_coupon($coupon_code);
        WC()->cart->apply_coupon($predefined_coupon_code);
        
        // Display a confirmation message
        wc_print_notice('Discount applied successfully!', 'success');
    }
}

This code doesn’t seem to apply the discount as intended. When entering a 5-character code, the predefined discount is not applied, and WooCommerce still treats it as an invalid coupon. They should simply enter a 5-character code, and the coupon should apply if the length condition is met.


Solution

  • You are not using the right filter hook for that. Try the following that will replace any 5 character inputted coupon code with a predefined coupon code:

    add_action( 'woocommerce_coupon_code', 'replace_5_char_coupon_code' );
    function replace_5_char_coupon_code( $coupon_code ) {
        // If the coupon code has exactly 5 characters
        if ( strlen($coupon_code) === 5 ) {
            $coupon_code = 'PREDEFINED50'; // coupon code replacement
        }
        return $coupon_code;
    }
    

    It should work.