Remove Posts and Pages from WordPress Search

This article shows you how to remove posts and pages from WordPress search and improve the search experience of your site.

If you are interested only in code snippets you can use Table of Content to navigate to that part right away. Otherwise, enjoy reading the whole article.

Introduction

WordPress search is one interesting and powerful feature that enables out of the box search. However, WordPress search will go through all of the pages on your website. Some of these pages or posts you won’t want in search results.

WordPress Search Mechanism

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 the search itself.

  • There are various plugins that help us accomplish this.
  • It’s not always a good solution to use a 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 the WordPress search mechanism.

Snippet 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' );

Explanation of the snippet

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

Now, we’re checking if that query is not an admin (we want admins to see everything), we’re checking if it’s searching and if it’s main_query. We want to add values to an 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 the array and they won’t be included in search anymore.

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

Summary

If you want to learn more about WordPress development, here is a book recommendation WordPress for Beginners 2021: A Visual Step-by-Step Guide to Mastering WordPress (Webmaster Series)

You can also examine other WordPress articles with more snippets and tips.