How to exclude certain posts or pages from your search results

The WordPress search results, by default, contain information from all available posts, pages, and custom post types. In some cases you might feel that you need to exclude certain items from the search results, because you feel that they contain irrelevant or confusing information. Today we’ll take a look at how we can achieve this.

The code

Edit your theme’s functions.php file and paste this at the bottom.

add_action( 'pre_get_posts', 'my_search_exclude_filter' );
function my_search_exclude_filter( $query ) {
  if ( ! $query->is_admin && $query->is_search && $query->is_main_query() ) {
    $query->set( 'post__not_in', array( 3, 11, 234, 553 ) );
  }
}

Modify the array bit in the highlighted line, and replace the numbers with the ids of the posts, pages, or custom post types you want to exclude from the search results page.

The function above will make sure that you are executing a search in the main query outside the administration pages. It will then pass the array of ids you have entered to theĀ post__not_in parameter of the WP_Query so they won’t be retrieved. That’s pretty much it.

If you need help finding the id of a certain item, please take a look at this article.

If you shy away from editing files, you can try using the search exclude plugin instead.

Subscribe to our newsletter.

Get fresh WordPress content straight into your inbox. We hate spam more than you do.

1 comment

  1. Norbert says:

    Hi Nik,

    Thanks for sharing this. Would like to exclude some certain post types from my search results and would rather use the above code than a plugin.

Leave a Reply

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