How To Create A Search Form For Your WordPress Blog

Problem

You would like your website visitors to be able to search for content in your website.

Solution

If you are building a blog, you certainly will like to allow your website visitors to search for blog posts. If that is the case you can add a simple form that will allow you visitors to enter a search term and get a list of posts that contains that keyword or term. The code below show how to define a input field with an id and name “s“, which by default is the variable WordPress expect to perform a search operation.

Example

Create a simple form that remembers the last search term

<div class="search-box">
    <h3>Search</h3>
    <form action="/" method="GET">
        <input 
            type="text" 
            id="s" 
            name="s" 
            value="{{if $smarty.get.s}}{{$smarty.get.s}}{{/if}}" 
            placeholder="{{if $smarty.get.s}}{{$smarty.get.s}}{{else}}Search for articles{{/if}}" 
            class="text-search">
        <input type="submit" value="" class="submit-search">
    </form>
</div>

 

Conclusion

The action of the form is set to the root (“/“), which will assure that the request will be capture by WordPress. Also notices that the value of the search text input field will be “empty” unless the variable “s” is in the page URL. This will allow render the last search term in case the result is empty, the visitor can modify his or her search term without having type the entire term.

Leave a Reply

Your email address will not be published. Required fields are marked *