Autocomplete in WordPress plugin admin

I just had to find a way to add autocomplete to an admin screen for a WordPress plugin I’m writing. Although a few pieces of jQuery UI are bundled into the WordPress distribution, that doesn’t include jQuery UI autocomplete. But on the way to investigating how to drop that into my plugin, I discovered that WordPress does bundle in a similar, simpler plugin called jquery.suggest.

Limitations

jquery.suggest isn’t as complex and configurable as jQuery UI autocomplete. In particular, it seems to be limited to utilising AJAX for results, whereas the jQuery UI one allows you to specify a JavaScript array as a query source. However, it is small and fast, caches search results, and… it’s already included in WordPress, so no additional maintenance required.

Installation

Because it’s distributed with WordPress, you can load it into your admin screens just by calling wp_enqueue_script with its predefined handle.

if (is_admin()) {
    wp_enqueue_script('jquery');
    wp_enqueue_script('suggest');
}

Then you add some script to your admin page to bind the suggest plugin to your input element. I’m binding to an input element with id=”DistRegion”. Note the value of the action parameter to the URL, which I’ll cover later.

jQuery(function($) {
    $("#DistRegion").suggest(ajaxurl + "?action=wpwines-dist-regions", { delay: 500, minchars: 2 });
});

NB: WordPress 2.8 and later define a variable called “ajaxurl” in JavaScript so that all scripts can find the AJAX URL easily. If you need to support an earlier version of WordPress, you’ll need to define this yourself.

Answering AJAX Queries

WordPress has a simple mechanism for dispatching AJAX queries to WordPress plugin code. You just add an action hook for your AJAX query, using an action name that you define, and queries will be delivered to your hook function. In the example above, I’ve called my action “wpwines-dist-regions”, so I need to hook into an action called “wp_ajax_wpwines-dist-regions”. The hook function is a method of my plugin’s admin class.

add_action('wp_ajax_wpwines-dist-regions', array($this, 'ajaxDistRegions'));

The hook function then needs to examine the query, and return a set of results to populate the suggest drop-down. My real hook function does a database query, but I’ve simplified the code here. The suggest plugin passes the search parameter as query parameter called ‘q’.

public function ajaxDistRegions() {
    $results = yourResultsFilter($_GET['q']);
    foreach ($results as $result) {
        echo $result . "n";
    }
    die();
}

NB: the hook function must terminate the PHP script at end, hence the call to die().

Nice, simple, fast, no mess. Job is done!

Facebooktwittergoogle_plusredditlinkedinmailFacebooktwittergoogle_plusredditlinkedinmail