Limit Contact Form 7 Submissions per Visitor
Allows only a few Contact Form 7 submissions per IP address each hour and treats the rest as spam, which stops bots and angry repeat senders flooding your inbox.
Opens WPIDE on
Code
$wpide_cf7_max_per_hour = 3; // Submissions allowed per IP address per hour.
$wpide_cf7_rate_key = function () {
$ip = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '';
return 'wpide_cf7_rate_' . md5( wp_salt() . $ip );
};
add_filter( 'wpcf7_spam', function ( $spam, $submission = null ) use ( $wpide_cf7_max_per_hour, $wpide_cf7_rate_key ) {
if ( $spam ) {
return $spam;
}
if ( (int) get_transient( $wpide_cf7_rate_key() ) >= $wpide_cf7_max_per_hour ) {
if ( $submission && method_exists( $submission, 'add_spam_log' ) ) {
$submission->add_spam_log( array( 'agent' => 'wpide-rate-limit', 'reason' => 'Too many submissions from this IP address.' ) );
}
return true;
}
return false;
}, 20, 2 );
add_action( 'wpcf7_mail_sent', function () use ( $wpide_cf7_rate_key ) {
$key = $wpide_cf7_rate_key();
set_transient( $key, (int) get_transient( $key ) + 1, HOUR_IN_SECONDS );
} );
Notes
IP addresses are stored only as hashes in short-lived transients; raise the limit for forms used from shared offices.
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.