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

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

## Code

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

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Limit Contact Form 7 Submissions per Visitor" 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/
