WordPress AJAX Live Search No jQuery Dependency

Here is a shortcode that I developed for WordPress to enable AJAX searching of the post title without relying on AJAX.  There is a big push to move away from using iQuery and just use native functions of the browser to achieve the same objectives.

My solution will detect when the shortcode is used and then only inject the CSS and JS dependent files when required.  The returned results include a feature image if available and a snippet of the post content.

To embed the search control within a page/post use the shortcode [es-ajax-search] .

Call the main search functions from your functions.php file by inserting the following line at the start of your file.

You might want to change the path of where the CSS, JS PHP files reside in the code below.  I create a directory called /inc, /css and /js directories under the child theme to store any custom code to keep it tidy.

Here is the jQuery free script for dealing with the AJAX calls.  It uses the fetch API and displays a basic CSS spinner to show you the code is executing.

Some CSS for styling the AJAX spinner and such.

That’s it, jQuery free AJAX searching in WordPress using the fetch API.  A modification that you might want to make it to include custom post types in the search result.  I’ve also limited results returned to the first 20 which can also me modified to suit your needs.

Leave a Reply

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