How to Search only Posts or Pages in WordPress

The WordPress search function by default will display all published pages and posts in the search results. While typically this setup is most ideal, there may however come a time when you only want to display your WordPress website’s posts or pages in the search results. In this tutorial we will teach you how to search only posts or pages in WordPress by utilizing PHP functions.

Search only WordPress Posts

In order to search only posts in WordPress, we will need to add a PHP filter to the WordPress functions file. Open your functions.php file then copy and paste the code below. Your WordPress site will now only return posts in the search results.

PHP

function SearchFilter($query) {
	if ($query->is_search) {
		$query->set('post_type', 'post');
	}
	return $query;
}

Search only WordPress Pages

In order to search only pages in WordPress, we will need to add a PHP filter to the WordPress functions file. Open your functions.php file then copy and paste the code below. Your WordPress site will now only return pages in the search results.

PHP

function SearchFilter($query) {
	if ($query->is_search) {
		$query->set('post_type', page);
	}
	return $query;
}

Troubleshooting

If you are having problems getting this tutorial to work please reread the tutorial and try again, if you still cannot get it to work please leave us a comment below and we will respond as soon as possible. Please do not email us with problems regarding this tutorial, only comments will be responded to.