Only Show Posts in WordPress Search Results

May 30, 2014 Development, PHP, WordPress

Only Show Posts in WordPress Search Results

By default, the WordPress search shows results from pages and posts. One client only wanted to search their blog posts and not the rest of the pages on the site.

This was solved by adding the following code to the theme’s function.php file. The code is quite simple and is very easy to read with WordPress’ well-named functions. If there is a search going on, then set the search to only look through the posts.

function SearchFilter($query)
{
	if($query->is_search)
	{
		$query->set('post_type', 'post'); // Posts only
		$query->set('post_status', 'publish'); // Exclude private posts
	}
	return $query;
}

add_filter('pre_get_posts','SearchFilter');

Going even further, we can even set which post categories to search through by changing the query->set parameters. In this example, the search will only look in categories 2 and 4.

$query->set('cat','2,4');

We can even reverse the code to only look through pages, which I’ve found to be useful as well.

$query->set('post_type', 'pages');

Thanks to c.bavota for the awesome filter.

Update

I’ve also set the post_status to publish so private posts won’t show in searches, even if the user is logged in.

Let's Talk About Your New Website

View Portfolio Contact Today