WordPress built-in search function searches all post types by default. Sometimes, we want to have some controls over what should be searched and what not. For example, on a blog website, I pretty much want to limit the search within “post” post type, but ignore “page”.
This could be done in two different options.
Option 1: Custom Search Form
In the search form, insert this line within the <form> tag.
<input type="hidden" value="post" name="post_type" id="post_type" />
There are two ways to add this hidden input field in the form.
- First is to alter the searchform.php. It should be in the theme folder. If the theme doesn’t include a (custom) searchform.php, default WordPress search form is called. You can still add a searchform.php to overwrite the default.
- The second method is to overwrite the search form using get_search_form() hook.
Both of these two methods are detailed in WordPress developer documentation here.
Option 2: pre_get_posts() hook
This hook is called after the query variable object is created, but before the actual query is run. This gives developers the power to alter the query.
// Limit search results by showing only results from POST function custom_search_filter($query) { if ( !is_admin() && $query->is_main_query() ) { if ($query->is_search) { $query->set('post_type', 'post'); } } } add_action('pre_get_posts','custom_search_filter');
If there are custom post types in your WordPress site, and you want to include them in search return, use array in line 5. For example, following code will also search custom post type “product”.
// Limit search results by showing only results from multiple post types function custom_search_filter($query) { if ( !is_admin() && $query->is_main_query() ) { if ($query->is_search) { $query->set('post_type', array('post','product')); } } } add_action('pre_get_posts','custom_search_filter');