Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm trying to include a jQuery autocomplete script in the header.php file of my theme.

The script, outside of wordpress, works great using this structure (which is the same as the jQuery autocomplete demo):

<script>
  $(function() {
     .....
  });
  </script>

I've tried wrapping it like this:

 <script>
jQuery().ready(function($) {
            $(function() {

            });
        });

      </script>

The original script works fine. Outside of wordpress I have no problem. It's when I try to add it to the header.php file that nothing works. Even other autocomplete scripts on the site stop working.

Also, I've added the following to my functions.php file:

function add_qa_scripts(){
  wp_enqueue_script( 'jquery-ui-autocomplete' );
}
add_action('wp_enqueue_scripts', 'add_qa_scripts');

I can see the scripts included in the footer of my theme. But, no matter what, I can't get the autocomplete to function. What am I doing wrong?

EDIT: As I'm not sure of the structural questions in the comments, here is the page for reference - the category tags should be auto completing:

http://bluepresley.com/qa/tag-search/

share|improve this question
    
note: there are various sources on the net that show very different ways of wrapping the script. None of them worked for me, and that is an example of what I found here: premium.wpmudev.org/blog/… –  user658182 May 12 at 15:40
1  
Can you verify that jQuery and jQuery UI are loaded before the autocomplete script? Chances are this is the issue. Unless you have different versions of jQuery running which you will then need to use no-conflict (api.jquery.com/jquery.noconflict). Is console throwing any errors? –  Jeremy May 12 at 15:45
1  
Did you try: ;(function($){ //code.. })(jQuery);? WordPress talks about jQuery.noconflict() in detail here: codex.wordpress.org/Function_Reference/… –  rafiki_rafi May 12 at 15:54
    
I'm actually not sure what I'm running or how the structure is comprised. The dev page is bluepresley.com/qa/ask-a-question The Category Tags are supposed to autocomplete. The same script works fine outside of wordpress (or, at least a very custom template that only includes jquery from the autocomplete demo) bluepresley.com/qa/tag-search - type in 'e' to see either working with my custom taxonomy. –  user658182 May 12 at 16:01
    
@Jeremy I didn't know this could be an issue. I not sure, but I'd have to say 'No' in response. I am adding my custom script in the head. Wordpress is adding the jquery ui and jquery autocomplete scripts in the footer. Would that cause a problem? –  user658182 May 12 at 16:13

2 Answers 2

up vote 1 down vote accepted

As I stated in the comments. You need to have jQuery and jQuery UI loaded in order to use the autocomplete UI. I modified your hook to have dependencies on the required libraries. Now all you need to do is set the path to your custom js file that initializes autocomplete. The dependencies will load the files needed as this is built into WordPress. You can see the available libraries here: wp_enqueue_script

function add_qa_scripts(){
    wp_enqueue_script(
        'my-autocomplete',
        PATH_TO_CUSTOM_JS_FILE,
        array(
            'jquery',
            'jquery-ui-core',
            'jquery-ui-autocomplete'
        ),
        '1.0.0', // version of custom js file
        true // always load in footer unless absolutely necessary
    );
}
add_action('wp_enqueue_scripts', 'add_qa_scripts');
share|improve this answer

There are a couple of ways to achieve this. I think the following methods are the best to use.

Method 1

Simply just add the script code directly to your functions file, and hook that function to wp_enqueue_scripts

    function enqueue_my_script() {
?>
<script>
  (function($){   
     $("#to").autocomplete({
      var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];
    function split( val ) {
      return val.split( /,\s*/ );
    }
    function extractLast( term ) {
      return split( term ).pop();
    }

    $( "#tags" )
      // don't navigate away from the field on tab when selecting an item
      .bind( "keydown", function( event ) {
        if ( event.keyCode === $.ui.keyCode.TAB &&
            $( this ).data( "ui-autocomplete" ).menu.active ) {
          event.preventDefault();
        }
      })
      .autocomplete({
        minLength: 0,
        source: function( request, response ) {
          // delegate back to autocomplete, but extract the last term
          response( $.ui.autocomplete.filter(
            availableTags, extractLast( request.term ) ) );
        },
        focus: function() {
          // prevent value inserted on focus
          return false;
        },
        select: function( event, ui ) {
          var terms = split( this.value );
          // remove the current input
          terms.pop();
          // add the selected item
          terms.push( ui.item.value );
          // add placeholder to get the comma-and-space at the end
          terms.push( "" );
          this.value = terms.join( ", " );
          return false;
        }
      });
     });
 })(jQuery);
</script>
<?php
}

add_action( 'wp_enqueue_scripts', 'enqueue_my_script', 999 );

Method 2

Create a file named for example 'my-script.js' inside your root or inside your js folder. Open that and add the jquery without your <script></script> tags. Here is the code to add in your js file

 (function($){   
     $("#to").autocomplete({
      var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];
    function split( val ) {
      return val.split( /,\s*/ );
    }
    function extractLast( term ) {
      return split( term ).pop();
    }

    $( "#tags" )
      // don't navigate away from the field on tab when selecting an item
      .bind( "keydown", function( event ) {
        if ( event.keyCode === $.ui.keyCode.TAB &&
            $( this ).data( "ui-autocomplete" ).menu.active ) {
          event.preventDefault();
        }
      })
      .autocomplete({
        minLength: 0,
        source: function( request, response ) {
          // delegate back to autocomplete, but extract the last term
          response( $.ui.autocomplete.filter(
            availableTags, extractLast( request.term ) ) );
        },
        focus: function() {
          // prevent value inserted on focus
          return false;
        },
        select: function( event, ui ) {
          var terms = split( this.value );
          // remove the current input
          terms.pop();
          // add the selected item
          terms.push( ui.item.value );
          // add placeholder to get the comma-and-space at the end
          terms.push( "" );
          this.value = terms.join( ", " );
          return false;
        }
      });
     });
 })(jQuery);

Now, using wp_enqueue_script(), register your jquery and hook that to the wp_enqueue_scripts hook

function enqueue_my_script() {
     wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/my-script.js', );
}

add_action( 'wp_enqueue_scripts', 'enqueue_my_script', 100 );

Just remember to change get_template_directory_uri() to get_stylesheet_directory_uri() if you are using a child theme.

For more reading, go and check the links I have provided.

share|improve this answer
    
One of the issues I'm having that's a point of confusion - do I need to enqueue the jquery-ui-autocomplete? Or did it suffice to add it to my functions.php file? So, in addition to that, I need to enqueue this script as well (in other words, it's a problem to simply manually add a script to the header.php file?) –  user658182 May 12 at 16:03
    
This script that you are talking about in your question, is this a custom script or the UI script. –  Pieter Goosen May 12 at 16:06
    
Actually, I'm new to this, so I'm not sure. More or less, this was copied straight from the jQuery UI autocomplete demo here: jqueryui.com/autocomplete/#multiple My dev page in question is here: bluepresley.com/qa/ask-a-question You can see the last script in the head is where it's located (if you want to take a look) thx! –  user658182 May 12 at 16:08
    
I've added no conflict mode. Please see update –  Pieter Goosen May 12 at 16:31
1  
Method 2 here looks like the best way to do this to me. You do also need to enqueue the jquery-ui though. The problem with just adding it to your header is that it doesn't meet WP standards one and two you would be running the script on every single page and not just those that need it. +1 to your answer @PieterGoosen –  Nick Young May 13 at 4:00

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.