Excluding Posts and Pages from Search

in WordPress Tutorials

At times it can be beneficial to prevent certain pages or posts showing up in your site’s search results. There are a variety of plugins that perform this sort of function for you, but if you’d like to do it yourself (which is typically better than a plugin), you can use the function below to exclude certain posts / pages.

1
2
3
4
5
6
7
8
9
// search filter
function my_search_filter($query) {
    // make sure we are not in the admin and that we are performing a search
    if ( !$query->is_admin && $query->is_search) {
        $query->set('post__not_in', array(40, 9) ); // IDs of pages or posts
    }
    return $query;
}
add_filter( 'pre_get_posts', 'my_search_filter' );

Now, when you do a search, neither the post/page with the ID 40 or 9 will show up.

You could take it a little further by also excluding all child pages of the excluding IDs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// search filter
function my_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 ID;
        }
        $query->set('post__not_in', $pages );
    }
    return $query;
}
add_filter( 'pre_get_posts', 'my_search_filter' );

You can also apply the same technique to other kinds of query results as well, not just searches. For example, you could us is_archive to hide posts from the archive pages.

Enjoy!