How to Build a Custom Search Page

by Matt Giovanisci | Last Updated: June 15, 2020

In order to create a custom search page, you will need to add 3 php files to your theme. So before you get started, just know this will require a bit of coding with no customer support. Code at your own risk.

I’ll try to make it as straightforward as possible by providing things to just copy and paste in the right areas.

1. Create a Search Form

The first thing we need to do is create the HTML form that people will be able to enter in search terms.

In your theme’s main folder, create a new PHP file called searchform.php. Then, copy and paste the following code in that file.

You can customize the form by changing the class in the <button>. Currently, it’s set to a blue-bg (blue background) with white text.

Hit save and now we have our search form that’ll look like this.

2. Create a Search Page

Now we need to create the page where this form will appear. First, we need to create another PHP file in the main theme folder called searchpage.php. Then, copy and paste the following code in that file.

Before you’ll see this on your site, you need to create a Page in WordPress and apply this new template. I recommend creating a page called Find.

You’ll also need to add some more styling code to your style.css file in order for this to look good.

Under the Forms section of the CSS file, add the following css classes to style the search input field:

.form-control{display: block; width: 100%; padding: 0.5rem 1rem; color: var(–black); background-color: #fff; background-clip: padding-box; border: 1px solid #ced4da; border-radius: 0.25rem; transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;}
.form-group{margin-bottom: 1rem;}

Clear your website cache and visit the /find/ page to see it in action. It should look like this:

Style this page however you want. The main thing is that the searchpage.php template will show the most recent 12 posts so it’s not just a blank page.

3. Create a Search Results Page

You’re not done yet. If you were to search something, it’ll just take you to the homepage and nothing will happen. You have to also build a results page.

Create a file in the theme’s main folder called search.php. Copy and paste the following code into that file:

This is very similar to the searchpage.php file except we now will display the search results. Like this…

And that’s it! You now have a fully functional search feature on your website. Remember, code at your own risk because there’s no support if you code this incorrectly. And feel free to style it however you want to work for yourself.

You can also include the searchform.php anywhere on your site.