WordPress has a simple function to build a search form for your blog and in this tutorial I'll show you how to add a category filter to it.
|
This function will look for a file called searchform.php inside your template folder: if it doesn't exist it will output the standard search form. So, if it isn't already in place, create your custom searchform.php and copy into it the default search form output. It should look similar to this:
|
We want to add a select box to let the user search in a specific category or in all categories: to achive this we'll use another default WordPress function.
The wp_dropdown_categories function will build for you a select box with all your categories. Take a look at the documentation for all the available options.
|
|
Now add the category select box to the form modifying your searchform.php like this:
|
That's it. It just works out of the box.
A finishing touch
Now that you have a nice category filter in your search form it would be great to modify the search result page and add something like Search result for “foo” in category “bar”. Well, it's quite easy: we need do add a simple function to the function.php file. Remember that every function in this file will be automatically available in your theme.
This is a simple function that gets the cat parameter from the request and if it's not null it searches the category name. It has two input parameters so you can pass two strings to be displayed before and after the category name. If cat is null or empty or “0” (All categories) it will return an empty string.
|
Now open you search.php, add the function call to the page and you are done:
|
Update 31.12.2011
Finally I wrote a blog post on adding a Multiple categories filter in WordPress search. Check it out!