/** Filter out spam messages on Gravity Forms using the Comment Blacklist * * @author Nikki Stokes * @link https://thebizpixie.com/article/reduce-gravity-forms-spam-entries-using-comment-blacklist/ * * Usage: Add spammy terms to Settings > Discussion > Disallowed Comment Keys to block form submissions * * @param string $is_spam, true if entry contains spam * @param array $form * @param array $entry */ function nhs_gforms_content_blacklist( $is_spam, $form, $entry ) { //DEBUG: Spit out entire structure of form object //print_r( $form ); // Get comment blacklist values (and only perform checks if there are terms in list) $mod_keys = trim( get_option( 'blacklist_keys' ) ); if ( '' !== $mod_keys ) { $words = explode( "\n", $mod_keys ); // Assign field content to variables foreach( $form['fields'] as $field ) { $id = $field['id']; if( $field['type'] == 'email' ){ $email = rgar( $entry, $id ); } if( $field['type'] == 'text' ){ if( $field['label'] == 'Contact Name' ){ $name = rgar( $entry, $id ); } if( $field['label'] == 'Phone' ){ $phone = rgar( $entry, $id ); } if( $field['label'] != 'Contact Name' && $field['label'] != 'Phone' ){ $text = rgar( $entry, $id); } } if( $field['type'] == 'textarea' ){ $message = rgar( $entry, $id); $message_without_html = wp_strip_all_tags( $message ); } } //DEBUG: Display values of fields for testing //echo "Email: $email
Name: $name
Phone: $phone
Company: $company
Text: $text
Message: $message
Clean Message: $message_without_html"; // 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, $phone ) || preg_match( $pattern, $text ) || preg_match( $pattern, $message ) || preg_match( $pattern, $message_without_html ) ) { $is_spam = true; break; } } } return $is_spam; } add_filter( 'gform_entry_is_spam', 'nhs_gforms_content_blacklist', 10, 3 );