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_plusredditpinterestlinkedinmailfacebooktwittergoogle_plusredditpinterestlinkedinmail
  • http://mdag.my Nuarharuha

    It work . I made a simple function to output username. pretty handy for filling up form. Thanks


    add_action('wp_ajax_mc-suggest-name', 'autocomplete_suggest_username');
    function autocomplete_suggest_username(){

    $users = get_users(array('orderby'=>'display_name','order'=>'ASC'));

    foreach($users as $index => $user){
    echo $user->display_name."n";
    }
    die();
    }

    • http://snippets.webaware.com.au/ Ross McKay

      Good work. Note that now, WordPress also bundles jQuery-UI’s autocomplete, so you can use that instead if you prefer.

      cheers,
      Ross

  • Craig Gwamba

    I’m trying to add “suggest” to a custom post field I created. Basically, I want to link a video post with an custom post type called “artist” using this input. In other words, when the user is on a video post they can type the title/name of the Artist and suggestions will show up based on artists already added/saved.

    However, Im struggling to get it working. I keep getting a response of 0 from the ajax request. Here is my code

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

    add_action('admin_head', 'add_script_config');
    add_action( 'wp_ajax_artist_names', 'ajaxArtistNames' );

    function add_script_config() {
    ?>

    jQuery(function($) {
    $("#artist").suggest(ajaxurl + "?action=wp_ajax_artist_names", { delay: 500, minchars: 2 });
    });

    5000,
    'order' => 'ASC',
    'orderby' => 'title',
    'post_type' => 'artist'
    );

    $artists_array = get_posts( $args );

    if ($artists_array) {
    foreach( $artists_array as $post ) : setup_postdata($post);
    $artist_title = get_the_title();
    echo $artist_title . "n";
    endforeach;
    }
    die();

    }

    This code is in my functions.php file so I’m sure the action must be accessible to the ajax call right? Any help would be most appreciated.

    Thanks.

    • http://snippets.webaware.com.au/ Ross McKay

      G’day Craig,

      Either your code got eaten by the comment system (very common!) or you’re missing something there. Can you post it into a Gist or Pastebin?

      A return code of 0 means your AJAX code isn’t being run, or isn’t being terminated.

      cheers,
      Ross