Exclude Posts and Pages in WordPress Search

Sometimes you don’t like to display every post and page on search results. Today I like to show you how to filter the search in your frontend. Therefore I add a filter to the query of WordPress and exclude the according posts or pages of the search.

We exclude posts and pages by their ID, which we will give to an array and so exclude several posts and pages.

In our first code example the IDs are set in the array. The filter is only working if it is the search is_search and if you are not ! in the backend is_admin.

// search filter
function fb_search_filter($query) {

    if ( !$query->is_admin && $query->is_search) {
        $query->set('post__not_in', array(40, 9) ); // id of page or post

    return $query;
add_filter( 'pre_get_posts', 'fb_search_filter' );

If you like to exclude the subpage of a page, then you can add it to the ID.

// search filter
function fb_search_filter($query) {

    if ( !$query->is_admin && $query->is_search) {
        $pages = array(2, 40, 9); // id of page or post
        // find children to id
        foreach( $pages as $page ) {
            $childrens = get_pages( array('child_of' => $page, 'echo' => 0) );
        // add id to array
        for($i = 0; $i < sizeof($childrens); ++$i) {
            $pages[] = $childrens[$i]->ID;
        $query->set('post__not_in', $pages );

    return $query;
add_filter( 'pre_get_posts', 'fb_search_filter' );

There are many possibilities and I hope I was able to give you a starting point if you like to exclude posts and pages in your search.

Comments are closed.


  1. Christopher Ross

    Great piece of code Frank. I needed to do something like this for my own site, so I took your example and added a little loop that’ll let me add posts dynamically.

  2. Benjamin L.

    Thx a lot for this post – very useful. I was wondering if there is a way to exclude a category from the search (?).

  3. Ricardo

    Hi, how can i exclude a whole category from WordPress search?

    Thanks in adavance

  4. Annie

    @Benjamin @Ricardo


  5. Benjamin L.

    Thanks Annie.

  6. Frank

    Thanks for the nice comments.
    To your asks for exlude a category: we had write before 2 posts about this topic, please see this different solutions:

  7. Randy

    This is awesome! I needed this for a site with a client portal that I just did. I knew how to hide one or more pages by ID but not for all future children pages.

    Really cool how much you can do with a simple function in WP vs. installing an entire plugin.

    Thank you!

3 pingbacks

  1. Tutorials :: Exclude Posts from Search Results in WordPress » thisismyurl.com
  2. Blog :: WordPress Wednesday for February 2nd, 2011 » thisismyurl.com
  3. Exclude Posts from Search Results in WordPress | The Helpful Coder