WordPress Custom Search

Ken Foubert

Here’s my scenario: I needed to create a custom search form to return WordPress posts based on Month/Year and Category and I figured that there has to be a way of doing that without adding another plugin.

I started with WordPress’s Codex entry on Creating a Search Page, it provides code snippets but doesn’t fully explain how to place the code. I’m going to iterate through the steps I used and hopefully others may find it helpful with their custom search.

NOTE: All these files will go in your theme folder, see the Folder Diagram Image

Wordpress Folder

Step 1

Add a new file called searchform.php – This file contains the code for creating the search form and will be included to your search pages. The very first few lines will be the code for preserving the search variables followed by the search form. In this example, it’s important to identify what we’re searching for, which is WordPress Posts, Month/Year, and Category, for WordPress filters we would use the following post/get form variables.

post_type[] = post
cat (short for Category Id)

Although its not exactly clear, there are a number of variables you can use on this WordPress codex entry to filter the search results.

Download the searchform.php sample code page, please be aware it is just sample code and has not been tested, you will need to modify it to make it work for you.

Step 2

Add a new file called searchpage.php. This is just a template that includes the search form and for displaying a default set of search results. You can download the sample code as a reference. To include the search form call this WordPress method, get_search_form(). WordPress will first look through your theme folder for a file named searchform.php, if there’s no file, it displays the standard built-in WordPress search form, please refer to the WordPress codex entry for get_search_form.

Step 3

The last step is to include the custom search form into the different search results. When posting the search form, the URL path changes based on the filters you used. For example, if I search just on Month and Year, the URL will look like this…


In contrast, if I just search for a category, then the URL will look like this…


Which means there are two or more different templates that we need to update to show the searchform.php form, depending on your theme. In my case I updated the following list of files and added the method to include the search form into the template.

Code snippet to add the search form to a template…
<section class="filter_bar">

<?php get_search_form(); ?>


Here’s a list of Files that I updated in mytheme to show the search form…

  • archive.php
  • content-none.php
  • index.php
  • searchpage.php (the custom search page template)

Files available for download