WordPress has an extremely rich search mechanism that not only searches for just posts, but can output pages, custom post types, or whatever result you want it to. But sometimes, you might want to hide certain posts from appearing on the search results. For example, a page that is only intended to list another list of pages and act as an index. You will not want it to appear when your users trying to find some actual content. In that case, here is the code snippet to exclude certain posts or pages from the in-built WordPress search.
Usage
- To build separate sections on your WordPress website where only certain posts will be displayed when the user searches for posts or pages.
- To prevent certain posts from appearing on the Google/Bing search results while search pages are indexed. For example, if you have a number of posts that you do not want to be indexed and you allow search engines to index certain search results.
- You are just writing the page or post for internal purposes which should be published but you do not want it to include in the search (we recommend setting a password or making it private instead).
Code
// Exclude Posts or Pages from WordPress search results using their IDs
function wpt_exclude_posts_from_search($query) {
if (!$query->is_admin && $query->is_search) {
$query->set('post__not_in', array(220, 344));
}
return $query;
}
add_filter( 'pre_get_posts', 'wpt_exclude_posts_from_search' );
You can use this code snippet for both posts and pages. Just make sure that the IDs you give inside the array()
is correct. If you don’t know how to find the post or page ID have a look at our article on different methods to get page ID.
Explanation
- Just a comment to identify the code block. It is recommended to leave it like that for easily differentiating the code.
- Creating a function
wpt_exclude_posts_from_search
and passing the$query
argument which is used to control the posts displayed on the page. - Making sure that we only execute the code if the current page is a search page and is not in the backend.
- Passing the post IDs as an array to
post__not_in
which is the parameter to exclude certain posts from the$query
. - Closing the if statement.
- Returning the filtered
$query
. - Closing our function.
- Adding the filter to the pre_get_posts hook which will be executed before the posts get displayed on the screen so that our filter will be applied.