Want to prevent pages from being displayed in the search result?
This article provides 2 methods to restrict the WordPress search function to only show posts in the search result.
1. Use custom filter
Create a new filter to exclude pages to be displayed in the search result. Just copy and paste the following PHP snippets into your theme’s functions.php
.
function wpb_search_filter($query)
{
if ($query->is_search)
{
$query->set('post_type', 'post');
}
return $query;
}
add_filter('pre_get_posts','wpb_search_filter');
2. Use WordPress plugin.
Download and install the WP – Fix search function plugin on your WordPress website. Done. This plugin will automatically insert the filter as noticed above into your WordPress.