How To show Search Results For Specific Post Types in WordPress

Friday , 2, July 2021 Leave a comment

show search results to specific post types is very very important thing for a web developer , Because if you search anything and you can see some unnecessary results like about us contact us, It is boring.

past the code in your functions.php file:

function searchfilter($query) {
 
    if ($query->is_search && !is_admin() ) {
        $query->set('post_type',array('post'));
    }
 
return $query;
}
 
add_filter('pre_get_posts','searchfilter');

Notice the line that says

$query->set('post_type',array('post'));

Now you can filter the search results by changing the values in the array variable. Right now it is set to display posts but you can modify it to display anything you want. post , page and custom post type etc.

Leave a Reply

Your email address will not be published. Required fields are marked *