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.
Opens WPIDE on
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
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.