Halloween Sale 15% off Ends in See the plans
PHP

Honeypot Trap for Contact Form 7

Adds a hidden field to every Contact Form 7 form that people never see but spam bots fill in. Submissions with the field filled are marked as spam and never emailed.

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

Code

$wpide_cf7_trap_name = 'wpide_company_url'; // Name of the hidden trap field.

add_filter( 'wpcf7_form_elements', function ( $html ) use ( $wpide_cf7_trap_name ) {
    $field = sprintf(
        '<span class="wpide-cf7-trap" aria-hidden="true" style="position:absolute!important;left:-9999px!important;width:1px;height:1px;overflow:hidden;"><label>Leave this field empty <input type="text" name="%1$s" value="" tabindex="-1" autocomplete="off"></label></span>',
        esc_attr( $wpide_cf7_trap_name )
    );

    return $field . $html;
} );

add_filter( 'wpcf7_spam', function ( $spam, $submission = null ) use ( $wpide_cf7_trap_name ) {
    if ( $spam || empty( $_POST[ $wpide_cf7_trap_name ] ) ) {
        return $spam;
    }

    if ( $submission && method_exists( $submission, 'add_spam_log' ) ) {
        $submission->add_spam_log( array( 'agent' => 'wpide-honeypot', 'reason' => 'The hidden trap field was filled in.' ) );
    }

    return true;
}, 10, 2 );

Notes

Change the field name if a bot learns it; keep it something a bot would want to fill, such as a website or company field.

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.