In WordPress, when you use the search form to search something, the result page contains POSTS and PAGES by default if it is Default WP_QUERY. Sometimes we don’t need Pages to be shown in search results or we need some Custom Post Type also to be included there.
Here is a code-snippet for that. Implementation is easy. I prefer Scripts Organizer.
Steps to implement :
<?php
function limited_search_filter($query) {
if ($query->is_search() && $query->is_main_query() && !is_admin()) {
$query->set('post_type', array('post')); //Limit to POSTS only
}
return $query;
}
add_filter('pre_get_posts', 'limited_search_filter');
or if you want to include any CPT also to the search result you can use below function instead.
<?php
function extended_search_filter($query) {
if ($query->is_search() && $query->is_main_query() && !is_admin()) {
$query->set('post_type', array('post', 'CPT_SLUG'));
//change CPT_SLUG to your CPT slug, like testimonials, reviews, products etc.
}
return $query;
}
add_filter('pre_get_posts', 'extended_search_filter');