Halloween Sale 15% off Ends in See the plans
PHP

Treat Contact Form 7 Messages in Foreign Scripts as Spam

Marks a Contact Form 7 submission as spam when most of its message is written in Cyrillic, Chinese or another script your business does not use.

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

Code

$wpide_cf7_blocked_scripts = array( 'Cyrillic', 'Han', 'Arabic', 'Hangul', 'Thai' ); // Unicode script names.
$wpide_cf7_script_share    = 0.3; // Share of letters in those scripts that marks a message as spam.

add_filter( 'wpcf7_spam', function ( $spam, $submission = null ) use ( $wpide_cf7_blocked_scripts, $wpide_cf7_script_share ) {
    if ( $spam || ! $submission ) {
        return $spam;
    }

    $text = '';
    foreach ( (array) $submission->get_posted_data() as $value ) {
        $text .= ' ' . ( is_array( $value ) ? implode( ' ', $value ) : (string) $value );
    }

    $letters = preg_match_all( '/\p{L}/u', $text );
    if ( $letters < 10 ) {
        return false;
    }

    $foreign = 0;
    foreach ( $wpide_cf7_blocked_scripts as $script ) {
        $foreign += (int) preg_match_all( '/\p{' . $script . '}/u', $text );
    }

    if ( $foreign / $letters >= $wpide_cf7_script_share ) {
        $submission->add_spam_log( array( 'agent' => 'wpide-script-filter', 'reason' => 'Message is mostly in a blocked script.' ) );
        return true;
    }

    return false;
}, 10, 2 );

Notes

Remove a script from the list if you do get genuine enquiries in that language.

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.