# Block Spam Searches

> Answers search requests that contain links, markup, very long strings or words you block with a 404, stopping bots from filling search pages with spam.

- Type: PHP
- Runs: Run everywhere
- Category: [Search](https://wpide.com/library/category/search/)
- Tags: search, spam, bots
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/block-spam-searches/

## Code

```php
// Searches longer than this many characters are treated as spam.
$wpide_search_max_length = 80;
// Words that mark a search as spam.
$wpide_blocked_search_words = array( 'casino', 'viagra', 'crypto loan' );

add_action( 'template_redirect', function () use ( $wpide_search_max_length, $wpide_blocked_search_words ) {
    global $wp_query;

    if ( ! is_search() ) {
        return;
    }

    $term   = (string) get_search_query( false );
    $length = function_exists( 'mb_strlen' ) ? mb_strlen( $term ) : strlen( $term );
    $spam   = $length > $wpide_search_max_length || preg_match( '#https?://|www\.|[<>{}\[\]]#i', $term );

    foreach ( $wpide_blocked_search_words as $word ) {
        if ( '' !== $word && false !== stripos( $term, $word ) ) {
            $spam = true;
        }
    }

    if ( $spam ) {
        $wp_query->set_404();
        status_header( 404 );
        nocache_headers();
    }
}, 1 );
```

## Notes

Add words to $wpide_blocked_search_words. Legitimate visitors rarely search for URLs, so they are blocked too.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Block Spam Searches" 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/
