jQuery Autocomplete not working with wp_localize_script

If you follow the second approach in the linked Q\A, you do not need ajax, but just to pass the array of terms to the script.

First of all in your functions.php (or equivalent) enqueue the script and pass the array of trades via wp_localize_script:

add_action( 'wp_enqueue_scripts', function() {

  /* you should check if the page is the one that include the form, you know how,
   * E.G.:
   *
   * if ( ! is_page( 'my-page-with-form' ) ) return;
   *
   */

  wp_enqueue_script(
    'my-theme-autocomplete', // is better to prefix everything in WP
    get_template_directory_uri() . '/assets/js/autocomplete.js',
    // put jquery-ui-autocomplete among dependencies
    array( 'jquery', 'jquery-form', 'json2', 'jquery-ui-autocomplete' ),
    NULL,
    true
  );

  wp_localize_script( 'my-theme-autocomplete', 'MyAjax_object', array(
    'all_trades' => implode( ',', get_terms( 'trade', array( 'fields' => 'names' ) ) )
  ) );

});

Now the autocomplete.js file should contain:

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

  $( '.main-search-field' ).autocomplete({
    source: MyAjax_object.all_trades.split(','),
    minLength: 1
  });

});

Notes

  • It is important to check if the page is the one that contain form, because otherwise the scripts (jquery, jquery-form, json2, jquery-ui-autocomplete and your autocomplete.js) will be added on every page, and also get_terms will always be called, slowing down page loading, so be sure to use the script only if needed.

  • In code above the autocomplete.js contain only 5 lines of code, and don’t worth to create an additional file only for that, if you have a javascript file you load on all pages (or that is loaded in the page where you need the autocomplete) put the code there, just be sure to adjust the handle (first argument) for wp_localize_script.

  • First code snippet uses an anonymous function (closure) so require PHP 5.3+.

Leave a Comment