Block IP Addresses From Contact Form 7
Silently rejects Contact Form 7 submissions from IP addresses or ranges you list, such as a persistent spammer, while the rest of the site stays open to them.
Opens WPIDE on
Code
$wpide_cf7_blocked_ips = array( '203.0.113.7', '198.51.100.' ); // Exact IPs or prefixes.
add_filter( 'wpcf7_spam', function ( $spam, $submission = null ) use ( $wpide_cf7_blocked_ips ) {
if ( $spam || ! $submission ) {
return $spam;
}
$ip = (string) $submission->get_meta( 'remote_ip' );
foreach ( $wpide_cf7_blocked_ips as $blocked ) {
$prefix = in_array( substr( $blocked, -1 ), array( '.', ':' ), true );
if ( ( $prefix && 0 === strpos( $ip, $blocked ) ) || $ip === $blocked ) {
$submission->add_spam_log( array( 'agent' => 'wpide-ip-block', 'reason' => 'Blocked IP address.' ) );
return true;
}
}
return false;
}, 10, 2 );
Notes
Supports exact addresses and prefix ranges ending in a dot or colon, such as 203.0.113.; behind a proxy CF7 reads the visitor IP it is given.
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.