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.
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.
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.
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
Andrew… I just want to say \m/
Thanks for Your JQuery Tutorial
It’s really helpful for me.
Thanks a lot
This needs to be updated to jQuery 1.4.0 by changing that call specifically
So simple. So perfect. Thanks!
thanks ı will try it .
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…
});
});
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’)); ?>
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
If I had Mootool or Jquery Old version.
How to avoid Jquery conflicts?
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 !
You need to look up the difference between cookies and caching ;)
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
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/
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
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.
…. actually wp_head is slightly wrong – it really is better to do it on ‘wp_enque_scripts’ like this
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)
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.
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:
Any suggestions would be much appreciated.
Hi Claudette,
The problem with the ��stuck’ URL you have posted is that it doesn’t exist – you need to ensure it is going directly to the Google APIs server without your own domain name being included. In the functions.php snippet you have included, you don’t need the pair of brackets around the ajax.googleapis URL. Just quotes (single or double) is fine.
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.
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
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!)
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.
Thank you! This SAVED me on an urgent project, I have been troubleshooting all day! Will share this post! Thanks again CSS Tricks!
Thanks!
This really helps. Thank you very very much.
Regards,
Prerak Trivedi.
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.
So is there an updated version of this snippet?
@Carl Hancock – very helpful and that definitely makes sense. Thanks for the good info.
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.
Is there a reason that this isn’t loaded in the footer by default?
I think it’s essentially because SO MANY plugins use wp_head to inject their scripts that if you default to footer with wp_enqueue_style you run the risk of breaking quite a lot of stuff.
OK – this seems to be reasonable but what if it comes to remove render-blocking issues? Ignoring this?
http://www.feedthebot.com/pagespeed/render-blocking.html
Oh I’m so confused even above the fold.
Cheers
Thomas
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.
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.
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…
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.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…..
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.
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:
As ever, thanks for the write up Chris!
Yea, I was about to say, couldn’t you just avoid the protocol parsing bit and just use protocol ambiguity? Thanks Yazin and Chris!
Excellent point, I was about to add this. May even save a hint of exec time to drop that protocol specification. Thanks Chris!
One more thing worth noting is that the
'wp_enqueue_scripts'
action does not run in admin requests, so theif (!is_admin())
isn’t really needed, although it does make clear the intention to the casual reader who may not be aware that there is a separate hook for admin ('admin_enqueue_scripts'
).I agree that because loading jquery from a cdn does away with the no-conflict aspect, this isn’t the greatest idea unless you are really in control of the end-use.
<
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
The intruccion says that put this code:
but it doesnt work , what can ido? or, which is the right way to put it in funtions PHP?
I realy preciate your help :)
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.
Is this correct?
The function call
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!
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…
I’ve been having the most difficult time including my jquery in WordPress. I’m trying to avoid having to deregister. After entering:
in function.php, how do I call my .js file correctly? Thanks!
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.
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.
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 [email protected]
greetings
martin
how can i upload my javascript from my static website and use it in wordpress
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:
`
‘
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’);
`
Very useful
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
This can probably improved to use protocol relative URLs (http://www.paulirish.com/2010/the-protocol-relative-url) to get rid of the whole http/https part:
Thanks. I found it very useful for me.
Hello Chris I have been using enqueue scripts, on a few WordPress sites work very well, I started to build a local WordPress site on my Mac using MampPro but for someone reason it’s not connecting to my css folder.
Using the .’css/custom.css’ even tried ../css any Ideas?
Eg:get_template_directory_uri().’/css/custom.css’ ); }
It’s a child theme twenty sixteen main style is fine.
Not a my Mac now post the code later
what we need to read :)