Grow your CSS skills. Land your dream job.

Last updated on:

Include jQuery in WordPress Theme

The following is the best way to go about it. Add the following to the theme's functions.php file:

if (!is_admin()) add_action("wp_enqueue_scripts", "my_jquery_enqueue", 11);
function my_jquery_enqueue() {
   wp_deregister_script('jquery');
   wp_register_script('jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", false, null);
   wp_enqueue_script('jquery');
}

Replace the URL with the location of what version of jQuery you want to use.

Reference URL

Comments

  1. Andrew
    Permalink to comment#

    Why is this the best method? What is the difference between this method and simply referencing it like <script type="text/javascript" src="/js/jquery-1.3.2.min.js">

    • Buddy, this one is to avoid Jquery conflicts i reckon.

    • Eric Montzka
      Permalink to comment#

      I believe it’s because jquery will download faster from googleapis, which is on many servers, than just the one your site is on.

    • Some plugins use jQuery. This way you’ll be sure jQuery doesn’t load multiple times.

    • vijay

      To avoid the jquery conflict the above code want to place on the function.php, tag is used for html.when u use mutiple jquery functionality in wordpress above code is useful

    • Permalink to comment#

      Andrew… I just want to say \m/

  2. Permalink to comment#

    Thanks for Your JQuery Tutorial
    It’s really helpful for me.
    Thanks a lot

  3. This needs to be updated to jQuery 1.4.0 by changing that call specifically

  4. So simple. So perfect. Thanks!

  5. thanks ı will try it .

  6. I can´t get jQuery to work with wordpress, I’ve been trying so many different things. Can you please look at my code, and see what’s wrong?

    $(document).ready(function() {
    $(‘.slideshow’).cycle({
    fx: ‘fade’ // choose your transition type, ex: fade, scrollUp, shuffle, etc…
    });
    });

  7. Sorry, my code was clipped…

    ?php wp_enqueue_script(‘jquery’); ?>
    ?php wp_enqueue_script(‘jquery-ui-1.8.2.custom.min’, ‘/wp-content/themes/nordborg/js/jquery-ui-1.8.2.custom.min.js’,array(‘jquery’)); ?>
    ?php wp_enqueue_script(‘jquery.cycle.min.js’, ‘/wp-content/themes/nordborg/js/jquery.cycle.min.js’,array(‘jquery’)); ?>

  8. William Topping
    Permalink to comment#

    Awesome,

    Thank you very much. I couldn’t get jQuery to work no matter what, yet when I added this in the functions it worked like a charm.

    So appreciative of this, I can carrying with coding instead of debugging.

    William

  9. If I had Mootool or Jquery Old version.
    How to avoid Jquery conflicts?

  10. It is in-fact important coz a lot of sites are using it and this js might already be present in the cookies of a user’s browser !

    • Helper
      Permalink to comment#

      You need to look up the difference between cookies and caching ;)

  11. gareth
    Permalink to comment#

    I am trying to move an existing site into WordPress for it’s CMS capabilities. The site uses the galleria classic theme from http://galleria.aino.se/. This works fine outside of wordpress, but as soon as it is added to wordpress, it no longer works and all I get is all of the images displayed one on top of the other. I have made each of my pages templates in order to not change any of the existing code except for adding the usual

    When I run the site in Firefox, Firebug gives the following error:

    Galleria is not defined
    [Break On This Error] Galleria.loadTheme(‘galleria.classic.min.js’);

    If anyone can help with this I’d really appreciate it, as I’ve been trying to work this out with my code for days. Please help!!!

    Please use the following link to view code:

    http://pastebin.com/W664Y2Ab

    Thanks

  12. David
    Permalink to comment#

    It still lacks the local version fallback in case they’re coming from China, Iran, or you don’t happen to have an internet connection at the moment, working on your localhost. There’s multiple ways, and I’m still not sure I’m a huge fan of it, but functionally it’s the best:

    beneverard.co.uk/blog/wordpress-loading-jquery-correctly-version-2/

  13. NB. THAT SNIPPIT IS OUT OF DATE. Use the most recent version from google (http://code.google.com/apis/libraries/devguide.html) if you’re getting it from google. Also note that if getting it from google you need to keep it updated. I know the google version is possibly faster because of local caching but by just using the wordpress version you dont have to remember to update your jquery, unless you need to be on the very latest version of jquery for some reason.

    • to use wordpress’s own version just add this to your functions.php

      function insert_jquery(){
         wp_enqueue_script('jquery');
      }
      add_filter('wp_head','insert_jquery');
    • Permalink to comment#

      Byronyasgur, the whole point is the advantages of including it from google – lots, and you’re doing the internet a favor. Yes, the simple way is just use the WordPress version.

      And as notes above, the link grabs the latest version from google, just as WordPress does. So worry about updating is not an issue.

      As for your snippet, part of the enqueue/register script function is whether or not to include it in the header or footer. By default it’s in the header, so adding the filter and function isn’t needed.

      And finally as mentioned, there’s no fallback to the local version included. I give the link above on the best way to do that.

      Why am I still discussing this? The internets have been over this. This is beginning to show the internet law that after x amount of comments, people stop reading them and they get reiterated.

  14. …. actually wp_head is slightly wrong – it really is better to do it on ‘wp_enque_scripts’ like this

    
    add_filter('wp_enqueue_scripts','insert_jquery');
    
    

    see – http://wordpress.stackexchange.com/questions/21561/where-is-the-right-place-to-register-enqueue-scripts-styles/21579#21579
    (previously the codex used to recommend init and i have seen other places recommended too)

  15. David,

    You may indeed be right about the google jquery method always taking the most recent version – in fact it would make much more sense …. but surely the version number still needs to be updated, or set to false or left out or something – what’s the point of it being ’1.3.2′ when jquery is at 1.7 or something ?

    Are you sure you’re right about the filter – did you notice it’s going in functions.php, not header.php. I dont think we can just throw wp_enqueue_script(‘jquery’);into the functions.php file without enqueuing it via a filter, and are you mistakenly thinking that wp_head has something to do with whether the script loads in the head or footer because I’m fairly sure it doesn’t. wp_head as far as I know is the ( actually incorrect as I later mentioned ) time that the enqueue is set to fire …. whether it eventually prints in the head or footer is selected rather via the last argument in wp_enqueue_script() ($in_footer) according to the codex.

  16. Claudette
    Permalink to comment#

    My site is painfully slow. I created it based on “murtaugh-HTML5-Reset-Wordpress-Theme-8aa6329″. I’m still working on it.

    According to Pingdom tools, one place it is getting stuck is here:

    http://www.MY-DOMAIN.org/ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js?ver=3.3.1

    In my functions.php, I have this code:

    if ( !function_exists(core_mods) ) {
    		function core_mods() {
    			if ( !is_admin() ) {
    				wp_deregister_script('jquery');
    				wp_register_script('jquery', ("http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"), false);
    				wp_enqueue_script('jquery');
    			}
    		}
    		core_mods();
    	}
    

    Any suggestions would be much appreciated.

  17. Carl Hancock

    ATTENTION WORDPRESS DEVELOPERS:

    Do the WordPress community a huge favor and NEVER implement jQuery this way in a theme you will be releasing to the public. Be it a commercial theme or a free theme that you plan on making publicly available.

    I would suggest that you ONLY implement jQuery this way on sites you yourself are running and managing AND sites that you will be making sure are always running the latest version of jQuery.

    If you are releasing a theme to the public (commercial or free) ALWAYS load jQuery simply by using the wp_enqueue_script(‘jquery’) call and NEVER deregister the built in jQuery and call it from an external source.

    WordPress Plugins developed using best practices enqueue jQuery via wp_enqueue_script(‘jquery’) and they expect that to load the version of jQuery that the current version of WordPress is using.

    If you have deregistered the built in jQuery call, and registered a call to an old version of jQuery on Google’s servers… you are asking for problems and headaches down the road.

    Why? Easy. You are changing the global WordPress environment for all other plugins and WordPress itself by doing this.

    If a plugin is expecting jQuery v1.7.1 because that is what is built into WordPress v3.3 and your theme comes along and it has reregistered jQuery and has registered jQuery v1.2.1 from Google’s servers? Shit’s going to break because you may have plugins that are expecting jQuery v1.7.1 and instead your theme is loading jQuery v1.2.1.

    WordPress comes with jQuery. It is updated every release. Do the community a favor and don’t change it unless you know what you are doing and you AREN’T releasing the theme to the public.

    Theme developers implementing jQuery this way cause countless hours of support for plugin developers and their users when they don’t know what they are doing.

    Implementing this is only appropriate on your own site. Loading jQuery should never be done this way in a theme that is being released to the public.

    • Efrat
      Permalink to comment#

      Chris Coyer: Please: I woukd much appreciate your answer to the claims brought about in the above comment. Do you agree? Do you defend your suggestion above? In what cases?
      The reason fo my request: I’m confused. The lack of response to such a remark as
      “Do the WordPress community a huge favor and NEVER implement jQuery this way in a theme you will be releasing to the public.”
      has confused me. Do you agree with the remark? Do you stand by your initial reccomendation?

      Thanks in advance -
      Efrat

    • Permalink to comment#

      Thanks for the tip, Cody. Seems like common sense to support a community one is developing specifically for, but so many times details like that just slip away from us! In the grand scheme of things, I can see how having a theme enqueue jQuery with WordPress’s method works better since the developer wont have to constantly update which version they load based on what the greater WordPress community is supporting (like the developers updating WordPress’s enqueue, and the developers writing the plug-ins that need to support their user bases…etc!)

      Strengthening the links and avoiding…a chain-reaction? (I don’t mean to be so cheesy. Ok, I lied. Yes I do!)

    • David
      Permalink to comment#

      Why not just call .noConflict() and enqueue jQuery Migrate immediately after enqueueing jQuery 1.9.1?

      Seems that the only difference between the WordPress version of jQuery and the Google version is that jQuery.noConflict(); is called at the end.

  18. Thank you! This SAVED me on an urgent project, I have been troubleshooting all day! Will share this post! Thanks again CSS Tricks!

  19. umaima
    Permalink to comment#

    Thanks!

  20. This really helps. Thank you very very much.

    Regards,
    Prerak Trivedi.

  21. Great way to include the jQuery library in WordPress, giving an include to the latest jQuery lib from Google APIs would prevent many bugs you may come across though. Either by using Google Git or jQuery’s URLs.

  22. nathaniel
    Permalink to comment#

    So is there an updated version of this snippet?

  23. Jimmy
    Permalink to comment#

    @Carl Hancock – very helpful and that definitely makes sense. Thanks for the good info.

  24. Carlos G
    Permalink to comment#

    I just cannot express how much I love you right now. Been sweating blood for 4 hours trying to find a solution and this is so simple and effective Im almost crying.

  25. Is there a reason that this isn’t loaded in the footer by default?

  26. Liam
    Permalink to comment#

    I’m pretty sure I am this down pat with some changes from the open post. I have concatenated all plugins together and required scripts to default to the footer.

    function scripts() {
        // Comment reply script for threaded comments.
        // Loading on single.php only.
        if ( is_single() AND comments_open() AND (get_option('thread_comments') == 1)) {
            wp_deregister_script( 'comment-reply' );
            //Removing the version number and loading in the footer
            wp_register_script( 'comment-reply', get_site_url() . '/wp-includes/js/comment-reply.js', array('jquery'), null, true );
            wp_enqueue_script( 'comment-reply' );
        }
        // If is not wp-admin
        if (!is_admin()) {
            //Removing the version number and loading in the footer
            wp_deregister_script( 'jquery' );
            wp_register_script( 'jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js", false, null, true);
            // Load Combined plugins and require jquery first
            wp_register_script( 'plugins', get_template_directory_uri() . '/js/plugins.js', array('jquery'), null, true );
            wp_enqueue_script( 'plugins' );
            wp_enqueue_script( 'jquery' );
        }
    }
    add_action( 'wp_print_scripts', 'scripts', 11); 
    

    Please note I have also re-registered comment-reply to hide the (WordPress) version number, load into the footer and on single.php only. Note the change from is_singular to is_single.

  27. Bert
    Permalink to comment#

    Just use one of the following links to get the version you want:

    http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js – Version 1.x.x
    http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js – Version 1.7.x
    http://ajax.googleapis.com/ajax/libs/jquery/1.7.4/jquery.min.js – Version 1.7.4
    http://code.jquery.com/jquery-latest.min.js – latest version

    Just my 2p…

  28. Bob Murphy
    Permalink to comment#

    The way that WordPress is setup you should not load from a CDN but always let WordPress use it’s own version of jquery; otherwise it may break stuff. wp_enqueue_script("jquery");The idea of getting it from the CDN sometimes doesn’t play nice with other wordpress plugins and scripts, that’s why the wordpress community doesn’t like it … even though it’s a good idea otherwise generally speaking.

  29. Ashok Saini
    Permalink to comment#

    hello dude, i want to put a downloaded slideshow in my wordpress theme….i have included javascript and css files………….but found difficulty in slides.php file while placing html codes in it…..please suggest…..

  30. This is fine if you NEVER EVER plan on distributing your theme, and you aren’t too worried about using plugins developed by the WordPress community.

    However, if you will be distributing your theme to other WordPress users, you will be doing the entire community a disservice by using Google’s jQuery. WordPress already includes a version of jQuery and you should use that version.

    Many theme devs decide not to use the version included with WordPress because it is in noConflict mode. You have to work just a little harder to make your js work with noConflict mode. So, getting rid of it and using Google’s (which is regular jQuery, not noConflict) seems like an easy way to avoid the extra few moments that it takes to program your js to work correctly.

    The problem is that you’ve now changed what every other developer expects WordPress to provide. They have developed their plugins to work with the included noConflict version of jQuery that WordPress is bundled with, and you’ve just pulled the rug out from under them and out from under anyone who will be using your theme.

    Deregistering the bundled version of jQuery and instead using Google’s version sounds nice at first, but causes tons of problems. Expect plugins to stop working at the very least. Instead, I implore everyone to please take some time to learn about how to create js to work with noConflict mode and just use what WordPress comes with – it will make your theme much stronger in the end.

  31. Permalink to comment#

    Ofcourse, you could always simplify it by using ‘//’ instead of the if statement – like so:

    wp_register_script('jquery', "//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", false, null);

    The complete code will now look like this:

        
        if (!is_admin()) add_action("wp_enqueue_scripts", "my_jquery_enqueue", 11);
           function my_jquery_enqueue() {
           wp_deregister_script('jquery');
           wp_register_script('jquery', "//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", false, null);
           wp_enqueue_script('jquery');
        }
        
    

    As ever, thanks for the write up Chris!

    • Blake Petersen
      Permalink to comment#

      Yea, I was about to say, couldn’t you just avoid the protocol parsing bit and just use protocol ambiguity? Thanks Yazin and Chris!

    • Permalink to comment#

      Excellent point, I was about to add this. May even save a hint of exec time to drop that protocol specification. Thanks Chris!

  32. Permalink to comment#

    <

    p>hello, thanks for the tip.

    <

    p>
    I have a problem installing a plugin inside my template in WP, and the only way to fix it according to the instructions of the plug-in is to place this code:

    This is my Funtions.php

    
    Funcion del tema
     '',
            'after_widget' => '',
            'before_title' => '',
            'after_title' => '',
        ));
    //insert jquery
    function insert_jquery(){
        wp_enqueue_script('jquery');
    }
    
    
    
    

    The intruccion says that put this code:

    
    if (!wp_script_is('jquery', 'queue')){
    wp_enqueue_script('jquery');
    }
    

    but it doesnt work , what can ido? or, which is the right way to put it in funtions PHP?

    I realy preciate your help :)

  33. Ernest Burnett
    Permalink to comment#

    Well…it’d be nice if WordPress actually included all of the working parts in one easy to work with ui file instead of having to hunt them all down to see if it will even work in WP – you guys ranting against CDN – it’s understandable but hey, in the end you are all giving bad advice – at least Chris is presenting an option while you folks are telling people flat out just don’t do anything – that makes no sense. Take Genesis Accordion for example, uses baked in jquery-ui…Instead your inputs should be more instructive on the proper methods for registering, enqueueing, and hooking (and also running in no conflict mode) because the fact is that people are not going to stop doing it simply because you don’t want them to…I’d be spending less time worrying about the CDN issue, and more time on making sure all your plugins work under 1.9 by the 29th.

  34. Is this correct?

    
    function include_jQuery() {
        if (!is_admin()) {
            wp_enqueue_script('jquery');
        }
    }
    add_action('init', 'include_jQuery');
    
    function include_jQuery() {
        if (!is_admin()) {
            // comment out the next two lines to load the local copy of jQuery
            wp_deregister_script('jquery'); 
            wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js', false, '1.9.1'); 
            wp_enqueue_script('jquery');
        }
    }
    add_action('init', 'include_jQuery');
    

    The function call

    
    jQuery(function ($) {
    });
    
  35. Kristin

    Thank you so much for this little snippet! Saved me today! One of our plugins broke due to the latest jQuery update. Hopefully I can figure out what the problem is for it with the latest version, but for now, this will do! Thanks so much!

  36. Ren

    HI!

    Just a quick question – I have a website that runs a slider that needs jQuery 1.6.0.
    So I want to build a condition in the functions.php like the below. I understand that it’s not possible to do such a thing in the functions.php – but how can I achieve this?

    That the is_front_page() uses jQuery 1.6.0 and the rest uses the latest version…

    function loadScripts() {
        if (!is_admin()) {
    if(is_front_page() ){ 
            wp_deregister_script( 'jquery' );
            wp_register_script( 'jquery', $scriptdir.'jquery.min.js', false, '1.6.0'); 
            wp_enqueue_script( 'jquery' );  
         }else{
         wp_deregister_script( 'jquery' );
        wp_register_script( 'jquery', 'http://code.jquery.com/jquery-latest.min.js', false, '1.9.1');
            wp_enqueue_script( 'jquery' );    
            wp_deregister_script( 'jquery-mig' );
        wp_register_script( 'jquery-mig', 'http://code.jquery.com/jquery-migrate-1.2.1.min.js', false, '1.2.1');
            wp_enqueue_script( 'jquery-mig' );  
         } ....
    
    
  37. Waymond
    Permalink to comment#

    I’ve been having the most difficult time including my jquery in WordPress. I’m trying to avoid having to deregister. After entering:

    wp_enqueue_script( 'jquery' );
    

    in function.php, how do I call my .js file correctly? Thanks!

  38. Permalink to comment#

    I found this after a good hour of banging my head against the desk. It worked perfectly where ten other resources failed. You da man, Chris.

  39. Blitz
    Permalink to comment#

    Great to see the WP enqueue code here on CSS Tricks and without a verbose article to go with it (when you are trying to get to the helpful code in a hurry and there’s a huge explanation first ;-), but perhaps, judging by the comments it is a little too brief.

    The reason scripts are best enqueued is (in no particular order):

    1) To be able to easily manage them from the functions.php file

    2) Order those scripts if necessary in the ‘queue’

    3) Use conditional statements to easily dequeue/enqueue (if you really must)

    4) Much more easily manage and troubleshoot conflicts

    5) Attempt to synchronise latest plugin release to a unified Jquery version where possible

    To answer the the ‘why is it like this?’ question is because historically, some plugins had poorly implemented JS/Jquery (and numerous different versions all at once – which fails anyway) and this causes huge perplexing conflicts as many of you are probably aware of. Using the enqueue system brings a certain order to using JQuery in WordPress, and certainly makes troubleshooting far quicker (and from experience far less common to do).

    The code snippet comes from the WordPress Codex: http://codex.wordpress.org/Function_Reference/wp_enqueue_script

    This page also (dryly) explains the enqueue system methods in more detail.

  40. hello dear developer

    just found your site – well i need help with Jquery:

    I RUN A TESTpage where i encounter an error

    probably i have some errors with jquery in WordPress:

    my WordPress seems to be a bit buggy -…-
    note – i run version – wp 3.8.1

    see the errory

    http://literaturen.org/wp/test/wp-admin/load-scripts.php?c=1&load%5B%5D=jquery-core,jquery-migrate,utils&ver=3.8.1 <!– see
    http://literaturen.org/wp/test/wp-admin/load-scripts.php?c=1&load%5B%5D=jquery-core,jquery-migrate,utils&ver=3.8.1 <!– see

    what can i do? Any and all help will greatly bea appreciated.

    just need your help
    you can contact me via martin.kaspar@campus-24.com

    greetings
    martin

  41. kevin

    how can i upload my javascript from my static website and use it in wordpress

    • Aaron
      Permalink to comment#

      You can just use one of two methods.

      1) Use tags. Here’s an example:
      &lt;script type=&quot;text/javascript&quot; src=&quot;/path-to/your-javascript.js"&gt;

      2) Registering and enqueuing your script. Here’s an example:
      `

    • Aaron
      Permalink to comment#

      You can just use one of two methods.

      1) Use tags. Here’s an example:
      <script type="text/javascript" src="/path-to/your-javascript.js”>

      2) Registering and enqueuing your script. Here’s an example:
      `
      wp_register_script(‘global’, (get_stylesheet_directory_uri() . ‘/assets/js/global.js’), ‘jquery’, ’1.0′, true);
      wp_enqueue_script(‘global’);

      `

  42. Shawn
    Permalink to comment#

    Very useful

  43. Joe Motacek

    You should not use a different version of jQuery for plugins or templates as it can cause conflicts with other plugins/templates/core parts of WordPress. (Unless you absolutely need to…)

    https://wordpress.stackexchange.com/questions/45437/including-jquery-and-javascript-files-the-correct-way/45440#45440?newreg=52b3c093eee841c4a1e1b7ab41736b9e

Leave a Comment

Posting Code

  • Use Markdown, and it will escape the code for you, like `<div class="cool">`.
  • Use triple-backticks for blocks of code.
    ``` 
    <div>
      <h1>multi-line block of code</h1>
      <span>be cool yo.</span>
    </div>
    ```
  • Otherwise, escape your code, like <code>&lt;div class="cool"&gt;</code>. Markdown is just easier though.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".