Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.