# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Forms](https://wpide.com/library/category/forms/)
- Tags: contact-form-7, spam, ip
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/cf7-block-ip-addresses/

## Code

```php
$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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Block IP Addresses From Contact Form 7" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
