Reject Contact Form 7 Submissions Sent Too Fast
Stamps each Contact Form 7 form with a signed time when it is shown and treats submissions sent within a few seconds as spam. People take longer than bots to fill in a form.
Opens WPIDE on
Code
$wpide_cf7_min_seconds = 4; // Minimum time between showing the form and submitting it.
add_filter( 'wpcf7_form_hidden_fields', function ( $fields ) {
$time = (string) time();
$fields['wpide_cf7_ts'] = $time . '.' . wp_hash( 'cf7-ts-' . $time );
return $fields;
} );
add_filter( 'wpcf7_spam', function ( $spam, $submission = null ) use ( $wpide_cf7_min_seconds ) {
if ( $spam ) {
return $spam;
}
$stamp = isset( $_POST['wpide_cf7_ts'] ) ? sanitize_text_field( wp_unslash( $_POST['wpide_cf7_ts'] ) ) : '';
$parts = explode( '.', $stamp, 2 );
$valid = 2 === count( $parts ) && ctype_digit( $parts[0] ) && hash_equals( wp_hash( 'cf7-ts-' . $parts[0] ), $parts[1] );
if ( $valid && time() - (int) $parts[0] >= $wpide_cf7_min_seconds ) {
return false;
}
if ( $submission && method_exists( $submission, 'add_spam_log' ) ) {
$submission->add_spam_log( array( 'agent' => 'wpide-time-trap', 'reason' => $valid ? 'Submitted too quickly.' : 'Missing or forged time stamp.' ) );
}
return true;
}, 10, 2 );
Notes
Works with page caching because older stamps always pass; raise the seconds for long forms if you see false positives in the spam log.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.