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.
Opens WPIDE on
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
- 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.