myBLOG-Online

Contact Form 7: block all URL’s in contact forms

Contact Form 7: block all URL's in contact forms

As someone who maintains multiple websites for my employer, which use Contact Form 7 for form functionality, I have been struggling with spam submissions, despite using Google Recaptcha, Akismet, and Honeypot for Contact Form 7, I was still getting a crap ton of link spam through our website forms.

The existing spam prevention measures outlined above blocked most of the bot spam, but unfortunately not all spam, either more sophisticated bots or real people filling out the forms were still getting past the trio of spam prevention systems. I had been searching for a while, when I came upon this WordPress functions.php snippet on Github, linked from a Stack Overflow thread, I found from a Google search!

However, it was not perfect out of the box, it stopped anything with ‘www’, https’ and ‘https’ in the URL, but if would allow yourdomain.tld (i.e. .com) through, so I added ‘.com’, ‘.net’, ‘.org’, ‘.xyz’, ‘.ga’, ‘.ly’ to the array, which are the most common URL extensions I receive spam from, see my altered code below;


add_filter( 'wpcf7_validate_text', 'no_urls_allowed', 10, 3 );
add_filter( 'wpcf7_validate_text*', 'no_urls_allowed', 10, 3 );
add_filter( 'wpcf7_validate_textarea', 'no_urls_allowed', 10, 3 );
add_filter( 'wpcf7_validate_textarea*', 'no_urls_allowed', 10, 3 );
function no_urls_allowed( $result, $tag ) {

	$tag = new WPCF7_Shortcode( $tag );

	$type = $tag->type;
	$name = $tag->name;

	$value = isset( $_POST[$name] )
		? trim( wp_unslash( strtr( (string) $_POST[$name], "\n", " " ) ) )
		: '';

	// If this is meant to be a URL field, do nothing
	if ( 'url' == $tag->basetype || stristr($name, 'url') ) {
		return $result;
	}

	// Check for URLs
	$value = $_POST[$name];
	$not_allowed = array( 'http://', 'https://', 'www.', '[url', '<a ', ' seo ', '.com', '.net', '.org', '.xyz', '.ga', '.ly' );
	foreach ( $not_allowed as $na ) {
		if ( stristr( $value, $na ) ) {
			$result->invalidate( $tag, 'URLs are not allowed' );
			return $result;
		}
	}
	return $result;
}

With the exception of my additional code for expanded functionality, I claim no credit for the above code, but I am very thankful to Gal Baras, who put this code up on Github. The battle with form spam has gotten out of hand, with dozens of spam messages received daily through our contact forms.

Finally, I did a test to make sure partial word matches are not blocked, for example, ‘complete’ or ‘network’, so you can use this script safely without fear of legitimate messages being blocked.

Have Something To Say About This Post? Please Comment Below!