jQuery Autocomplete with WordPress

Assuming you know something about plugin development, I want to share a piece using jQuery autocomplete the WordPress way.

Ajax calls have been around and jQuery autocomplete has been, but you do not see them as much together in examples the WordPress way.

var aj_data;
var cache = {};

(function ($, root, undefined) {

    'use strict';

    function p_get_posts(term, suggest) {
        // ajax call
        jQuery.ajax({
            // we have set aj_data with localize to the enqueue file
            url : aj_data.ajax_url,
            type : 'post',
            data : {
                action : 'p_get_posts',
                nonce  : aj_data.nonce,
                search : term
            },

            success : function( response ) {
                cache[ term ] = response;
                suggest(response);
            }
        });
    }



    $(document).ready(function($) {

        // Select search box
        $('.search-field').autocomplete({
            minLength: 3,
            source: function ( term, suggest) {
                // term.term is the 3 letters 
                var termout = term.term;
                // check if these letters have been searched before
                if ( termout in cache ) {
                    // set the suggestion list to hold the cache
                    suggest( cache[ termout ] );
                    return;
                }
                // if searchterm letters are new
                p_get_posts(term, suggest);
            }
        });

    });


})(jQuery, this);

The included scripts

function front_assets_load() {
    if (is_admin()) return;

        // we give these values to the javascript
	$value = array(
	    'ajax_url' => admin_url( 'admin-ajax.php' ),
	    'nonce' => wp_create_nonce('ajax_nonce')
	);

        // enqueue autocomplete the wordpress way
	wp_enqueue_script('jquery-ui-autocomplete', '', array('jquery-ui-widget', 'jquery-ui-position'), '1.12.1');
	/* Enqueue theme script & style */
	wp_enqueue_style( 'your-stylesheet', get_stylesheet_uri()  );
        wp_enqueue_script( 'your-js', get_template_directory_uri() . '/assets/javascript/dist/scripts.js', array('jquery', 'jquery-ui-autocomplete'));
	// with localize we hook the value in aj_data to the script
        wp_localize_script('your-js', 'aj_data', $value);
    /* Enqueue comment-reply script if needed */
    if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
		wp_enqueue_script( 'comment-reply' );
	}
}
add_action('wp_enqueue_scripts', 'front_assets_load');

// we set to trus the action named p_get_posts to use the function
add_action( 'wp_ajax_p_get_posts', 'p_get_posts' ); // for loggedin users
add_action( 'wp_ajax_nopriv_p_get_posts', 'p_get_posts' ); // for guests

And the function to get posts

function p_get_posts() {

	check_ajax_referer('ajax_nonce', 'nonce');

	$return = array();
	//$return[] = $_POST['search']['term'];
	$posts = get_posts(array(
		's' => $_POST['search']['term'],
		'posts_per_page'   => -1
	));

	foreach ($posts as $key => $post) {
		$return[] = $post->post_title;
	}

	wp_send_json($return);

}