Limit WordPress Search Results to Certain Post Types

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.

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.

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”.

 

 

Comments are closed.

Post Navigation