internet search engine 1433323 1920

Remove Posts and Pages from WordPress Search

You want to remove Posts and Pages from WordPress?

Search mechanism and search results are very important. Furthermore, they are part of every WordPress web site.

Usually, WordPress web sites have lots of “helper” pages that provide important functionalities. Yet again, sometimes they shouldn’t be included in search itself.

  • There are various of plugins that helps us accomplish this.
  • It’s not always a good solution to use new plugin for every small task.
  • This is because our Web site can end up with tons of plugins, lots of updates etc.

Instead of installing a plugin, there is a small code snippet. This snippet can help us exclude specific pages from WordPress search mechanism.

Quick script to Remove Posts and Pages from WordPress

/*
* This is a function that removes specific pages from search query
* We only need to add ID's to our array, and that pages/posts will be excluded
*/
function wp_search_filter( $query ) {
if ( ! $query->is_admin && $query->is_search && $query->is_main_query() ) {
$query->set( 'post__not_in', array( 126,102,145 ) );
}
}
add_action( 'pre_get_posts', 'wp_search_filter' );

We created a function wp_search_filter and we invoked it on $query object.

Now, we’re checking if that query is not admin (we want admins to see everything), we’re checking if it’s search and if it’s main_query. We want to add values to attribute called post__not_in , where we keep IDs of pages that we don’t want to see in search results.

It’s that simple! Simple script to Remove Posts and Pages from WordPress.

So, just find IDs of your pages (in our example it’s 126,102 and 145), add them to array and they won’t be included in search any more.

Note: This will work for any kind of posts (Posts, Pages, Attachments, etc.) on our web site.

Just to make it clear, learn difference between WordPress posts and pages.

Finally, if you want to learn more about WordPress check out some of the other posts.

Enjoy!