Skip to content

Instantly share code, notes, and snippets.

@thebizpixie
Created March 1, 2024 03:38
Show Gist options
  • Save thebizpixie/e27d9e0ac8bb02795a65af7cef4accee to your computer and use it in GitHub Desktop.
Save thebizpixie/e27d9e0ac8bb02795a65af7cef4accee to your computer and use it in GitHub Desktop.
WPForms spam prevention using the Disallowed Comment Keys field in Wordpress
/** Filter out spam messages on WPForms forms **/
// Stop form entry being saved, and don't send emails, if it contains spam terms
// @link https://measurewhatworks.com/article/stop-wpforms-spam-using-comment-blacklist-field/
function nhs_stop_spam_entry_saving( $save_entry, $fields, $entry, $form_data ){
$contains_spam = nhs_check_blacklisted_terms( $fields, $entry, $form_data );
/* If entry is spammy, don't save it or send any email notifications */
if( $contains_spam ){
$save_entry = false;
add_filter( 'wpforms_disable_all_emails', function(){ return true; } );
}
return $save_entry;
}
add_filter('wpforms_entry_save', 'nhs_stop_spam_entry_saving', 9, 4);
/** Check form entry against spam terms in discussion blacklist field **/
function nhs_check_blacklisted_terms( $fields, $entry, $form_data ){
$contains_spam = false;
// Get comment blacklist values
$mod_keys = trim( get_option( 'blacklist_keys' ) );
if ( '' == $mod_keys ) {
}
else{
$words = explode( "\n", $mod_keys );
// Assign field content to variables
foreach( $fields as $id => $field ) {
if( 'email' == $field['type'] ){
$email = $field['value'];
}
if( 'name [first]' == $field['type'] ){
$first_name = $field['value'];
}
if( 'text' == $field['type'] ){
$text = $field['value'];
}
if( 'textarea' == $field['type'] ){
$message = $field['value'];
$message_without_html = wp_strip_all_tags( $message );
}
}
// Step through spam terms in turn
foreach ( (array) $words as $word ) {
$word = trim( $word );
// Skip empty lines
if ( empty( $word ) ) {
continue; }
// Escape terms so that '#' chars in the spam words don't break things
$word = preg_quote( $word, '#' );
// Match form fields to spam terms
$pattern = "#$word#i";
if ( preg_match( $pattern, $name )
|| preg_match( $pattern, $email )
|| preg_match( $pattern, $text )
|| preg_match( $pattern, $message )
|| preg_match( $pattern, $message_without_html )
) {
$honeypot = '[Blacklist] ' . $name . ', ' . $email . ', ' . $message;
$contains_spam = true;
}
}
}
return $contains_spam;
}
@thebizpixie
Copy link
Author

Make sure to read the full blog post to understand how to use this code:
https://thebizpixie.com/article/stop-wpforms-spam-using-comment-blacklist-field/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment