If you have a WordPress website, you may have noticed that by default, WordPress includes all types of content such as posts, products, pages, image file URLs, PDF file URLs, and more in search results. This can be a turnoff for your site users and make your search results page look very messy. To limit the search results to only display posts, you can copy and paste the code snippet below into your theme’s function.php file.
However, it is recommended that you create a child theme and paste the code into the function.php file of the child theme instead. This is to avoid breaking anything on your website when you try to edit the original theme. Furthermore, if you update the original theme in the future, your code will remain intact in the child theme. If you paste the code in the original theme, it might be overwritten whenever you update it.
If you do not know how to create a child theme, don’t worry. Watch the video below and follow it step-by-step.
if (!is_admin()) {
function wpb_search_filter($query) {
if ($query->is_search) {
$query->set('post_type', 'post');
}
return $query;
}
add_filter('pre_get_posts','wpb_search_filter');
}