Family Encyclopedia >> Electronics

How to Create an Advanced Search Form in WordPress for Custom Post Types

Have you ever worked on a WordPress site that has many custom post types? WordPress search is a mess, which is why many bloggers use Google custom search. Well, we were working on a site that has a good number of resource articles, videos, books, and blog posts. Using the default WordPress search just wasn't cutting it. Using Google search was also not a viable option. Therefore, we decided to create an advanced search form that allows the user to choose the area of ​​the site they want to search by limiting custom post types via checkboxes. Users can combine their search queries, and more importantly, we made it so that the checkboxes are saved along with the search query. This allows the user to see exactly what they searched for, and they can modify the parameters. In this article, we will show you how to create an advanced search form in WordPress using the power of the WordPress search query and limiting the results by custom post types.

The first thing to do is open your searchform.php file or wherever your search form is stored. Then add the following fields inside the form code:


Don't forget to replace the value with your custom post types. The above code basically limits the search results to those post types. Well, if you noticed, we pretty much added all available post types except Pages. Well, there is a good reason to do that which we will see later. So make sure you include ALL post types you want to search for using the main search button. These fields are hidden, so the user does not see them.

Next, open your search.php file and paste the following code above the content of the loop, so your users can see the options at the top.


Artículos Blog Libros Videos

This will add a search box above your results with the search query inside the input box. This will also check what post types are being searched for in the query and tick the appropriate checkboxes. Remember, how we added all post types in the hidden field. Well, we added it just so we can run the in_array check and keep the boxes checked. There was no documentation on how to do this otherwise, so this was the best way we found the job. Here's a preview of what the search box looks like:

How to Create an Advanced Search Form in WordPress for Custom Post Types

From there, the user can simply modify the parameter to their liking.

Hopefully this article has helped those in need. When we're doing the research, there were a lot of incomplete articles. I found the answer of adding the checkboxes on the WordPress support forum in a previous thread, however they were only referring to hidden fields. Whereas we wanted to give users the option to modify the search query. Props to @tammyhart for pointing out the correct way to do the check query for the variable.