Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.