Halloween Sale 15% off Ends in See the plans
PHP

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.

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

Code

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