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.
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:
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:
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.