AJAX WordPress Search

You know when you type a search in Google and then it always shows some suggestions below, well recently I had a client who wanted something very similar using their WordPress site. This posts looks at how I implemented a similar feature to a site to show any posts as suggestions, which met the search criteria.

The site in question was a recruitment site and one that I was tasked with integrating my ever increasingly popular WP Broadbean plugin with. Therefore the site had lots of job posts, which are a custom post type and the clients requirements were that the user should be able to search for a job by title (and other parameters which are not relevant here so I won’t go into those details).

The client was very insistent that when the user starts typing in the search box that the site should then show a list of suggested job posts under the search input which matched their criteria without the page refreshing. Therefore in order to do this we would have to query the jobs on the fly as the user was typing. In other words we would have to use AJAX.

AJAX stands for Asynchronous Javascript and XML and to put it simply it means that you can get new data onto a webpage without the page itself refreshing. This is exactly what we need. We can use Javascript (jQuery is what I know – ish!) to fire an event off when the user starts typing in the input box. To do this the following javascript can be used:

https://gist.github.com/wpmark/26f323481687b96eb1ab

We now have to hook this file into WordPress. To do this you use the normal WordPress enqueue scripts with the extra step that we need to localise the script. We do this like so:

https://gist.github.com/wpmark/e75171c627a5bab395b0

The final step is to actually write the function that will do the query for us. This, like the code above can be done in a plugin file or in your themes functions.php file. The code below completes this for us:

https://gist.github.com/wpmark/2d03441a7dbd4bd2a06f

And there you have it a search input that when you type it returns post titles that match like the search criteria you have entered.

5 thoughts on “AJAX WordPress Search”

  1. Hi Mark,

    Thanks for the article, it works a treat! Any idea how you would also include wordpress tags and categories in this?

    Regards,
    Benji

  2. Superb stuff. I am going to use this for my next project. Any idea how to use filters with this? There seem to be very few articles about this stuff. Thanks!

  3. Mark it looks like your function myplugin_ajax_job_search() was going to return the $output, but you ended up echoing it instead. is there a reason for that?

    Thanks for posting this.

Leave a Reply

Your e-mail address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.