How to Make a WordPress Settings Autocomplete Field Using Ajax

When building the admin settings page for Holler Box, I needed to let the user select a page or taxonomy.

I could have built a select menu, but if you have a lot of items it can quickly get out of control.

This also doesn’t allow for multiple items, so instead I found a nifty way to use a text field with autocomplete. Holler Box now has autocomplete for all of the display filters, it looks like this:

Click to view

I was surprised to learn that there is actually an ajax function built into WordPress core that allows you to do this. It’s called ajax-tag-search, and there is no official documentation for it that I could find.

The ajax tag search function works with post categories and tags, here’s how to use it.

WordPress Ajax Tag Search

WordPress uses an old jQuery plugin called Suggest which is pre-configured to get items and place them into your text field. To use it, we need to enqueue a script in the WordPress admin on our settings page. (I’m assuming you already have an admin settings page created)

Mine looks like this:

add_action( 'admin_enqueue_scripts', function() { 
  wp_enqueue_script( 'holler-pro-js', Holler_Box_Pro_URL . 'assets/js/holler-pro' . $suffix . '.js', array( 'suggest' ), Holler_Box_Pro_VER, true );
});

Notice the dependency on the jQuery suggest script, that makes sure the plugin is available.

If you don’t already have a text field on your settings page, go ahead and add one. For example:

<input type="text" placeholder="Start typing a category name" class="widefat" name="hwp_show_on_cats" id="hwp_show_on_cats" value="<?php echo get_post_meta( $id, 'hwp_show_on_cats', 1 ); ?>" size="20" />

Next, in our admin Javascript file, we need to activate the autocomplete on this field.

In my holler-pro-js file, I can add something like this:

(function(window, document, $, undefined){

var hpadmin = {};

  hpadmin.init = function() {

    $('#hwp_show_on_cats').suggest( window.ajaxurl + "?action=ajax-tag-search&tax=category", {multiple:true, multipleSep: ","});

  }

  hpadmin.init();

})(window, document, jQuery);

You’ll notice the &tax=category at the end of the url string, you can change that to post_tag if you’d like to search tags.

That’s it, you should now have an autocomplete field that saves!

Remember that this will be stored as a string, for example: “My Category, Another Category” etc. You’ll need to deal with this appropriately, for example you can use PHP explode if you’d like an array instead.

What about Post Types, Custom Taxonomies, etc?

The limitation of ajax tag search is that it only searches default post taxonomies. It does not work with custom taxonomies, or post types.

The good news is that it’s really easy to create your own ajax function to handle other things like post types. For example, Holler Box has a field to add pages, so I needed to search pages by title. I copied the ajax_tag_search function and changed it to search for pages:

add_action( 'wp_ajax_hwp_ajax_page_search', function() {

            $s = wp_unslash( $_GET['q'] );

            $comma = _x( ',', 'page delimiter' );
            if ( ',' !== $comma )
                $s = str_replace( $comma, ',', $s );
            if ( false !== strpos( $s, ',' ) ) {
                $s = explode( ',', $s );
                $s = $s[count( $s ) - 1];
            }
            $s = trim( $s );

            $term_search_min_chars = 2;

            $the_query = new WP_Query( 
                array( 
                    's' => $s,
                    'posts_per_page' => 5,
                    'post_type' => 'page'
                    ) 
                );

            if ( $the_query->have_posts() ) {
                while ( $the_query->have_posts() ) {
                    $the_query->the_post();
                    $results[] = get_the_title();
                }
                /* Restore original Post Data */
                wp_reset_postdata();
            } else {
                $results = 'No results';
            }

            echo join( $results, "\n" );
            wp_die();
});

Then in my Javascript file, I added this line:

$('#show_on_pages').suggest( window.ajaxurl + "?action=hwp_ajax_page_search", {multiple:true, multipleSep: ","});

It’s identical to the tag search we did above, but I just changed the action to use my ajax callback. Here’s what that looks like:

You could make that work for custom taxonomies or other post types as well by editing the WP_Query arguments.

Ready to get more leads and sales?

Use Hollerbox to design and deploy popups faster.

1 thought on “How to Make a WordPress Settings Autocomplete Field Using Ajax”

Leave a Comment

Scroll to Top