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.
Opens WPIDE on
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
- 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.