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

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

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

function firstwd_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’,’firstwd_searchfilter’);

Sign up for Envato Elements and get unlimited downloads starting at only .50 per month!

DOWNLOAD NOW

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

This post may contain affiliate links. See our disclosure about affiliate links here.

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!

Posted by WordPress Guru