internet search engine 1433323 1920

How to remove specific Posts and Pages from WordPress Search

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

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

There are various of plugins that helps us accomplish this, but it’s not always a good solution to use new plugin for every small task, 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, that can help us exclude specific pages from WordPress search mechanism.

* 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!

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.


Leave a Comment

I am preparing online courses "Python for Beginners" and "Software Design Patterns"

Reserve your FREE spot by subscribing to my newsletter.
Once courses are completed you will receive entrance coupon and full access to this course.