Restricting WordPress search

I needed to stop certain content appearing in any search on a WordPress so here’s how…

function my_no_restricted($search,$wp_query)
{
global $wpdb;
if ( empty( $search ) )
return $search;
$q = $wp_query->query_vars;
$n = ! empty( $q['exact'] ) ? '' : '%';

$searchand = ' AND ';
foreach ( (array) $q['search_terms'] as $term ) {
$term = esc_sql( $wpdb->esc_like( $term ) );
$search .= "{$searchand}($wpdb->posts.post_content NOT LIKE '%DONT SEARCH ME%')";
$searchand = ' AND ';
}
return $search;
}
add_filter( 'posts_search', 'my_no_restricted', 500, 2 );

Replace DONT SEARCH ME with whatever you want to prevent being searchable!
Just pop it in a theme/plugin function.php file

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.