WordPress: How To Exclude Pages From Search Results

When performing a search on a WordPress site, by default the results will be posts and pages. Usually when people are searching on a blog, they are most likely to be looking for a post rather than a page. There are two ways to exclude pages from showing up in search results.

The first method will completely block pages from search results. Simply copy and paste the below code into your functions.php file:

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

The second method gives the user the choice of searching for posts, pages or both. This is done by changing the way your search form works. The following code should replace the code of your current search form:

<form id="searchform" action="/" method="get">
<input type="text" name="s" placeholder="Search..." />
<select name="post_type">
<option>Posts</option>
<option>Pages</option>
<option>Both</option>
</select>
<button>Search</button>
</form>

Explanation: So, by adding the select with the name of “post_type” it adds a string to the search URL telling WordPress to only search for posts or pages. For example, the following URL will show only posts: https://www.thewebtaylor.com/?s=exclude+pages+search&post_type=post

Free Graphics, Icons, Tutorials
Free Graphics Free Christmas Vector Icon Graphics Pack 2017Free Fitness Vector Icons Graphics PackFree Camping Vector Graphics PackFree Summer Graphics PackFree File Icon PackFree Fast Food Vector Graphics
Sharing is caring...
Like & Follow
Share the love, share this page! Facebook Twitter Digg Reddit LinkedIn Pinterest Email
Close [X]
The Web Taylor
1000 Lakeside North Harbour Portsmouth, Hampshire PO6 3EN
02392 123358