jQuery UI Autocomplete showing all results

You get all terms because you’re asking for all terms, in fact, the line

$tradeList = get_terms('trade');

just get all the terms, ignoring the ‘term’ query string passed to file.

If you want to get all the terms “filterd” you have to use the string in the query, something like:

include_once( '../../../wp-load.php' ); // adjust the path, of course
// or dirname( dirname( dirname( __FILE__ ) ) ) . '/wp-load.php';
$term = filter_input( INPUT_GET, 'term', FILTER_SANITIZE_STRING );
if ( empty( $term ) ) exit();
$trades = get_terms( 'trade', array( 'name__like' => $term, 'fields' => 'names' ) );
if ( ! empty( $trades ) && is_array( $trades ) ) {
  echo json_encode( $trades );
}

That said, note that by using settings in OP, everytime an user type a char in the input field, there is an ajax request to your server, so if user type 4 letters before make a choice, you’ll have 4 additional http requests, so that code easily becomes a server killer.

So, if you want to use this approach, at least use an higher minLength argument.

An alternative is to get all terms, output them as javascript array and let the script make the filtering, something like:

$(document).ready(function() {
  var trades = <?php
  $trades = get_terms( 'trade', array( 'fields' => 'names' ) );
  echo '["' . implode( '","', $trades ) . '"]';
  ?>;
  $(".main-search-field").autocomplete({
    source: trades,
    minLength: 1
  }); 
});

Doing so there is no additional http request, there is no need of any autocomplete.php file and unless you have thousands of trades terms, this approach is probably better.

Notes

In the first approach, the rough including of wp-load.php is a bad practice, I know you are doing it to “don’t overhead the server”, but the bad news is that the overhead for the server don’t decrease so much in this way: you’ll load all the WordPress environment, all the plugins and the theme. In addition be aware that it makes your code unsuitable to be shared. If the code is only for you and you really want to use this approach, search for SHORTINIT constant and its usage (start here) and load wp-load.php hardcoding the location path (like I did) because $_SERVER['DOCUMENT_ROOT'] is not affordable, it may be not the expected value depending on how server is configured.

The second approach I suggested, saves you from the wp-load.php problem, and also saves your server from a great number of requests, but that PHP code echoed in the javascript is something really bad, I used only for sake of semplicity in this answer. You should put your javascript code in a separate js file and pass to it the terms using wp_localize_script.

Leave a Comment