Menu

Exclude specific sites or posts from the built-in WordPress search

Published on 11/06/2021

The built-in WordPress search might not be the greatest, and there’s plenty of extensions to give it some more power (I’m personally a big fan of SearchWP). For simple sites though, it just does the job, so I often stick with it.

One thing I’m often in need of is a slight modification of WordPress search results. For example, the front page is often just a summary of other contents, so it might not be relevant as a search result. Another case might be to exclude specific pages or posts from the results. Luckily, there’s a few snippets we can work with.

Exclude the front page from WordPress search results

The search results page is just another query™. This means we can use the pre_get_posts filter to target search results on the frontend. Here’s a little snippet that excludes the front page from WordPress search results:

function cr_search_filter( $query ){
	if( $query->is_search && $query->is_main_query() && !is_admin() ) {
		$front_page = (array)get_option( 'page_on_front' );
		$query->set( 'post__not_in', $front_page );
	}
}
add_action( 'pre_get_posts', 'cr_search_filter' );

What’s happening here? We’re hooking into pre_get_posts and first check whether we’re on the search results page, on the frontend and in the main query. If that’s the case, we’re pulling the front page ID from the options and exclude it via post__not_in. And voilá, front page gone from the search results.

If we wanted to exclude a whole category of posts from the search results, we could use category__not_in, like so:

$query->set( 'category__not_in', 7 );

You can basically apply any query argument here.

Leave a comment