How To Limit WordPress Search Results By Post Type

There are occasions in which you may want to limit WordPress search results to a specific post type rather than just the default. Your theme may have custom post types that you want to be included in the search, or perhaps you only want to search the custom post type and not posts or pages. This is relatively simple to do without a plugin, which is usually best practice when possible.

UNLIMITED DOWNLOADS: 500,000+ WordPress & Design Assets

Sign up for Envato Elements and get unlimited downloads starting at only $16.50 per month!




 

Open your theme’s functions.php file and copy the following code snippet at the bottom.

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

Note the line where it says

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

Change that line where it says ‘post’, ‘page’ to whatever post type you want the search to be filtered through. So, for example, your code would look like this:

function 1wd_searchfilter($query) { 
    if ($query->is_search && !is_admin() ) {
        $query->set('post_type',array('custom_post_type_name_1','custom_post_type_name_2'));
    } 
return $query;
} 
add_filter('pre_get_posts','1wd_searchfilter');

Be sure to change the name of the custom post type to your own.

We hope that helps you next time you need to limit WordPress search results by post type. Be sure to check out our other WordPress tutorials for more useful tips!