How to Change the Cache Time on Your Form Token

Overview

Would you like to control the cache time on your form token? You can easily add some PHP to set these times yourself and we’ll show you how!

First you may be asking how exactly this works. Form tokens are unique to the form and will expire and be reset when a certain amount of time has passed.

When using honeypot, a spammer can make a direct $_POST request to your site without ever actually loading the webpage or form. So a form token will reject that submission because the form token was not included on submission. If a spammer would try to hard code the form token it would still fail because of each token is unique and expires after a certain amount 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.

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


	// Create our array of times to check before today. A user with a longer
	// cache time can extend this. A user with a shorter cache time can remove times.
	$valid_token_times_before = apply_filters(
		'wpforms_form_token_check_before_today',
			[
				( 2 * DAY_IN_SECONDS ), // Two days ago.
				( 1 * DAY_IN_SECONDS ), // One day ago.
			]
		);

	// Mostly to catch edge cases like the form page loading and submitting on two different days.
	// This probably won't be filtered by users too much, but they could extend it.
	$valid_token_times_after = apply_filters(
		'wpforms_form_token_check_after_today',
		[
			( 45 * MINUTE_IN_SECONDS ), // Add in 45 minutes past today to catch some midnight edge cases.
		]
	);


	// Example use of the token:
	add_filter( 'wpforms_form_token_check_before_today', 'example_add_longer_token_time_before' );

	/**
	 * Extend the expiration time. 
	 */
	function example_add_longer_token_time_before( $times ) {
		// Allow the token to persist for 5 days
		$times[] = 3 * DAY_IN_SECONDS;
		$times[] = 4 * DAY_IN_SECONDS;
		$times[] = 5 * DAY_IN_SECONDS;
	}

	add_filter( 'wpforms_form_token_check_after_today', 'example_add_longer_token_time_after' );



	/**
	 * This filter is to catch edge cases of someone loading the form and submitting,
	 * with the expiration happening in between. Making this longer allows for more leeway.
	 */
	function example_add_longer_token_time_after( $times ) {

		$times = array( DAY_IN_SECONDS );
	}

Look for the comments in the snippet for further explanation and detail.

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: