# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Forms](https://wpide.com/library/category/forms/)
- Tags: contact-form-7, spam, validation
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/cf7-no-links-in-message/

## Code

```php
$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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Block Links in Contact Form 7 Messages" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
