How to Change the Cache Time on Your Form Token

Overview

Are you interested in having control over the cache time for your form token? We can guide you on how to achieve this by adding PHP code.

Let’s begin by understanding how it works. Form tokens are specific to each form and are set to expire and reset after a certain duration.

When utilizing a honeypot, spammers may attempt to send a direct $_POST request to your website without actually loading the webpage or form. However, the form token will reject such submissions because the form token was not included in the request. Even if a spammer tries to hard code the form token, it will still fail because each token is unique and expires after a specific period of time.

Adding the code snippet

If you would like to control the cache time for the form tokens, just copy this snippet to your site and adjust the times as needed.

If you need assistance in how and where to add snippets to your site, please review this tutorial.


/**
 * Extend cache time on form tokens before today.
 *
 * @link https://wpforms.com/developers/how-to-change-the-cache-time-on-your-form-token
 */

function example_add_longer_token_time_before( $times ) {
    // Allow the token to persist for 3, 4, and 5 days
    $times[] = 3 * DAY_IN_SECONDS;
    $times[] = 4 * DAY_IN_SECONDS;
    $times[] = 5 * DAY_IN_SECONDS;

    return $times;
}
add_filter( 'wpforms_form_token_check_before_today', 'example_add_longer_token_time_before' );

/**
 * Extend cache time on form tokens before today.
 *
 * @link https://wpforms.com/developers/how-to-change-the-cache-time-on-your-form-token
 */

function example_add_longer_token_time_after( $times ) {
    // Allow the token to persist for 1 day
    $times[] = DAY_IN_SECONDS;

    return $times;
}
add_filter( 'wpforms_form_token_check_after_today', 'example_add_longer_token_time_after' );

Look for the comments in the snippet for further explanation and detail on each function.

And that’s all you need to change the cache time on form tokens! Are you using GDPR but can’t get the flag on the Smart Phone form field to load correctly? No worries, just check out our snippet on How to Enable GDPR Without Removing the Smart Phone IP Auto-detection.

Filter References: