Halloween Sale 15% off Ends in See the plans
PHP

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.

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

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

  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.