Custom spam filter with Contact Form 7, no extra plugins needed

I have been receiving more and more spam through one of my sites’ contact form, which uses Contact Form 7. To help stop this, I created a simple custom function that blocks contact form messages that contain specific words, without any additional plugins or services.

There are several ways to deal with spam sent through Contact Form 7, but many involve yet another plugin, paid services, annoying captchas, math quizzes, etc. If you just want to stop contact form messages that contain specific words, you can add a filter in your site’s functions.php file.

For example, the latest spam rage seems to be all about “dating” sites (really?). Almost all of the spam has the same key words, which luckily are ones that nobody would actually use in a contact form for a software consulting business (and I’m not particularly looking for any dating sites as clients). The spam words that come up most for me are “dating”, “datings”, “personals”, and “singles”.

The filter code I use checks the subject line for these words, and throws a validation error and message if any of these words appear in the subject line. It’s not sophisticated, and can be easily defeated by a human, but it will stop most run of the mill spam bots.

Here’s the function:

// Contact form 7 custom validation for spam in subject lines
add_filter( 'wpcf7_validate_text', 'custom_text_confirmation_validation_filter', 20, 2 );

function custom_text_confirmation_validation_filter( $result, $tag ) {

    // Add your spam words below, separated by '|'
    $spam_words = "dating|datings|personals|singles";

    // Specify the name of the Contact Form 7 field that you want to check for spam
    $filter_field = "your-subject";

    if ( $filter_field == $tag->name ) {
        $your_subject = isset( $_POST[$filter_field] ) ? trim( $_POST[$filter_field] ) : '';

        if ( preg_match("/(" . $spam_words . ")/i", $your_subject) === 1 ) {
            $result->invalidate( $tag, "Please don't spam this contact form." );
        }
    }

    return $result;
}

Change the $spam_words to match whatever words you want to used.

You will also need to replace and/or match $filter_field (which is ‘your-subject’ in the code above) to the name of the Contact Form 7 field name that you use for your subject line. You can check this in your contact form editor, like this:

Once the function has been added to functions.php and customized, you will have some basic anti-bot spam filtering on your Contact Form 7 form:

You can also use the same function to check the message body if your spam situation is getting out of hand, but it may be worth checking other options.

Leave a Reply

Your email address will not be published. Required fields are marked *