Follow us:
By default, WordPress search includes everything—posts, pages, and sometimes even custom post types created by themes or plugins. While this might seem helpful, it can clutter results and make it harder for visitors to find what they’re actually looking for.
Imagine running a site with blog posts, products, and a portfolio. If someone searches for “SEO,” they probably want to see blog content, not your service pages or portfolio items. That’s where restricting search to specific post types becomes useful. It keeps results focused and improves user experience without needing an extra plugin.
In this guide, you’ll learn a simple way to limit search results to only the post types you want, using a small code snippet.
1. Add the Search Filter Code
Open your functions.php file (in your theme or child theme), then paste the following code:
function wp_passion_filter_search($query) {
if ($query->is_search && !is_admin()) {
$query->set('post_type', ['post', 'page']);
}
return $query;
}
add_filter('pre_get_posts', 'wp_passion_filter_search');
What’s happening here:
$query->is_searchchecks if the current query is a search.!is_admin()ensures the filter only applies to front-end searches (not the admin dashboard).$query->set('post_type', [...])tells WordPress exactly which post types to retrieve—in this case, both ‘post’ and ‘page’.
You can adjust this to your needs—maybe ['post', 'portfolio'] or just ['product']—depending on your site’s content.
2. Why It Works
This snippet hooks into the pre_get_posts action, which lets you modify search queries before WordPress sends them to the database. It’s lightweight, efficient, and requires no plugin installation.
3. Pro Tips for Smooth Usage
- Test thoroughly if you have multiple search forms or AJAX-based search.
- Keep the admin area unrestricted—that’s why
!is_admin()is essential. - Use clear labels if you’re guiding users to specific searches (like “Search Products” vs “Search Blog”).
In short: A few lines of code are all it takes to control which post types appear in your WordPress search. This keeps results clean, relevant, and tailored to your site’s purpose.



