Categories
Advanced Tutorials

Add HTML Search with Autocomplete in WordPress

Let me show you how to create a form with plain HTML, override the existing WordPress get_search_form() function, and give you a couple of ideas on autocomplete.

Codeable.io

Let me show you how to create a form with plain HTML, override the existing WordPress get_search_form() function, and give you a couple of ideas on autocomplete.

The Form

I have coded a quick demo of how to create the plain HTML search form without using any JavaScript. All we need to do is add input of type search and link it with a datalist HTML element.

Note: Styling a datalist with CSS is tricky, but it’s not impossible.

Get Search Form

Now that we have a sample of our plain HTML search form, let me show you how to integrate it and override the WordPress function responsible for generating and outputting a search form.

Now it comes to the tricky part how-to load the datalist options with terms from your database post and page content.

  1. You can generate a list with 100 most searched terms and put them into a JSON file. Then create the datalist options based on this list. You can use Google Analytics or create a method (use plugin) to filter and list the most common words from your content. And finally, run a corn job update this list weekly (or daily if you blog very active and you publish one or more articles each day).
  2. The second option would be to create an autocomplete function, however, for this, you would need to add a JavaScript event listener on key-down for the input search. And then add a couple of ajax functions to select and load the terms from your database.
  3. Only if you already have jQueryUI within your project loaded I would recommend using their autocomplete feature.

What’s Next?

You have seen from this tutorial that you don’t need to use a plugin to create a fancy and easy WordPress search form with autocomplete. And for sure, you would need a very minimal usage of JavaScript to get it working.

If it were up to me, I would combine options #1 and #2 to generate the datalist options. If you want to know how to do that, please comment below, and if I get more than several requests, I will write a second post of this tutorial where I will show you how to add an autocomplete functionality to your plain HTML search form.

‘Til the next one.

Leave a Reply

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