Block Links in Contact Form 7 Messages
Shows an error when a message field contains more web links than you allow. Most contact form spam exists to place links.
Opens WPIDE on
Code
$wpide_cf7_max_links = 0; // Links allowed in a textarea field.
$wpide_cf7_link_check = function ( $result, $tag ) use ( $wpide_cf7_max_links ) {
$text = isset( $_POST[ $tag->name ] ) ? (string) wp_unslash( $_POST[ $tag->name ] ) : '';
if ( '' === $text ) {
return $result;
}
$links = preg_match_all( '#(https?://|www\.|\[url|<a\s)#i', $text );
if ( $links > $wpide_cf7_max_links ) {
$result->invalidate( $tag, 0 === $wpide_cf7_max_links ? 'Please remove the links from your message.' : sprintf( 'Please include no more than %d link(s).', $wpide_cf7_max_links ) );
}
return $result;
};
add_filter( 'wpcf7_validate_textarea', $wpide_cf7_link_check, 20, 2 );
add_filter( 'wpcf7_validate_textarea*', $wpide_cf7_link_check, 20, 2 );
Notes
Set the allowed number of links to 1 or 2 if customers often send you a link to their site.
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.