5 Tips For Using jQuery with WordPress

Having used jQuery and WordPress together on a number of plugins and themes, I thought I’d share some tips that I have learned. The following are 5 clear, concise, and relevant tips that you should know when using jQuery in your WordPress Theme or Plugin.

1. Use wp_enqueue_script()

The traditional way to include jQuery in an HTML page is with the script tag. When working with WordPress, you should *never* do this. To avoid conflicts and other potential problems, you’ll want to load jQuery using the following code:

function my_init() {
	if (!is_admin()) {
		wp_enqueue_script('jquery');
	}
}
add_action('init', 'my_init');

You can replace my_init with something more meaningful, but choose a unique name to avoid conflicts. For plugin development, add the code in your plugin file, otherwise, add this code to your theme’s functions.php file. The is_admin() check is to prevent script queuing on your admin pages.

WordPress References:

2. Load jQuery from the Google AJAX Library

Since WordPress includes jQuery, calling wp_enqueue_script('jquery'); will automatically load the jQuery file located in wp-includes/js/jquery/jquery.js.

If you want to load jQuery from the Google AJAX Library, you’ll need to modify the code as follows:

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

There are a number of reasons why you would want to use the Google AJAX Library to load jQuery, but remember, Google has been down before, so be ready to comment out the first two lines if necessary.

Note: As mentioned by Milan in the comments, there are existing plugins, such as Use Google Libraries, that will do this for you.

3. Load jQuery in the footer

Using the code in the previous two tips, jQuery will, by default, be inserted into the head of your HTML page. If you would prefer to have jQuery inserted at the bottom of your page, you’ll need to use the $in_footer parameter for the wp_enqueue_script() function. The modified code:

function my_init() {
	if (!is_admin()) {
		wp_deregister_script('jquery');

		// load the local copy of jQuery in the footer
		wp_register_script('jquery', '/wp-includes/js/jquery/jquery.js', false, '1.3.2', true);

		// or load the Google API copy in the footer
		//wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js', false, '1.3.2', true);

		wp_enqueue_script('jquery');
	}
}
add_action('init', 'my_init');

As with the choice to use the Google AJAX Library, there are reasons why you’d want to load jQuery at the bottom of your page. Note: if a script is loaded using wp_enqeue_script() that lists jQuery as a dependency and has $in_footer set to false, WordPress will place jQuery in the head instead of the footer, regardless of the $in_footer value for jQuery.

4. Add jQuery as a dependency

You’ve got jQuery loading and now you want to include a script that uses it. This is where the wp_enqueue_script() function really comes in handy. By passing an array of dependencies for the $deps parameter, WordPress will automatically manage the order and placement of your script tags.

For example, if you have a JavaScript file in your theme that leveraged jQuery, the following code would ensure that your file is loaded correctly:

function my_init() {
	if (!is_admin()) {
		wp_deregister_script('jquery');
		wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js', false, '1.3.2', true);
		wp_enqueue_script('jquery');

		// load a JS file from my theme: js/theme.js
		wp_enqueue_script('my_script', get_bloginfo('template_url') . '/js/theme.js', array('jquery'), '1.0', true);
	}
}
add_action('init', 'my_init');

The previous code example would load jQuery from the Google AJAX Library, place it in the footer of your page and then include your theme.js file. The $deps array allows for multiple dependencies and helps you manage the scripts that are loaded on your site.

5. Proper jQuery coding conventions

All of the previous steps are nullified if proper jQuery coding conventions aren’t followed. The most common issue I see with jQuery and WordPress is the misuse of the $ variable.

It is important to know that the version of jQuery that comes with WordPress automatically calls the jQuery.noConflict(); function, which gives control of the $ variable back to whichever library first implemented it. If you are loading a different copy of jQuery, you’ll need to manually call jQuery.noConflict();, if necessary, from one of your JavaScript files.

As a general rule, you should not use the $ variable for jQuery unless you have used one of the shortcuts. The following is an example of how to shortcut jQuery to safely use the $ variable:

jQuery(function ($) {
	/* You can safely use $ in this code block to reference jQuery */
});

This is the second article in a series of tips and tricks for customizing and improving your WordPress site. Be sure to subscribe or bookmark this site.

If you have any other related WordPress tips, feel free to leave them in the comments below.

42 thoughts on “5 Tips For Using jQuery with WordPress”

  1. You shouldn’t make hacks to load jQuery or any other JavaScript library from Google AJAX Libraries, and instead you should encourage use of plugin that solves this, Use Google Libraries. Website owners should themselves decide do they what to serve files from Google’s servers or not, and also you should always try to use existing solutions available through plugins and not to made unnecessary hacks.

    Please update your post with that information.

    (btw, you should enable Subscribe to comments plugin for easier tracking of replies on comments)

  2. @Milan – thanks for your input.

    The purpose of this post was to provide some insight into how the wp_enqeue_script() function works and the importance of using it.

    I’ll leave it up to the readers to decide whether they want to use an existing plugin or not. I prefer to try things on my own to understand how they work, but I don’t consider that a hack or unnecessary 😉

    I tried the “subscribe to comments” plugin in the past without any luck, perhaps I should take another look. Thanks for the suggestion.

  3. Hi Eric: I would like to include a script on a specific Page or Post in WordPress. What would an IF statement look like to accomodate that?

    For instance, I wrote a little script for GA that loads up only today’s stats so you don’t have to shuffle through all the menus and dropdowns. It works great as link on my static test, but now I’d like to post this to either an article or a page (I may feature it as a page later, but as a post for now). How do I include the little script only exacty where I need it so that it doesn’t load up all the time for every page on the site?

    Thanks,

    Doug

  4. @Doug – have a look at the WordPress Conditional Tags page. You’ll want to do something similar to how I used is_admin() in the code samples above, but using the conditional tag that is appropriate to your needs.

    Contact me directly if you have any further questions regarding this.

  5. Thanks for this. I’ve been looking for some documentation on exactly how to deal with jQuery conflicts. My theme framework has been getting hammered with plugins wrecking stuff. I’m going to be testing this by adding plugins to see how they perform, but this will be used in the next release.

  6. @Hollie Phillips – thank you. I think we can all agree that what I’ve covered on this topic is not hacking, but valuable information that can help people working with jQuery and WordPress.

    @Tim Bednar – glad to have helped. One thing I learned is that no matter how much you try to avoid conflicts, it only takes one other plugin (that does not follow the conventions) to mess every thing up 😉

  7. Pingback: The best way for including Jquery into wordpress with no conflicts | SAOB | Senseless Acts of Beauty

  8. Pingback: Jimmy » Use Jquery in WP themes

  9. Great post, Eric. Nice to see someone demonstrating a much asked about, but too often unused, method in WordPress.

    I’ll have to try to keep this post in mind to refer others to 🙂

    Also, installing the “Subscribe to Comments” plugin would be great! If you’re having trouble with it not sending emails, I’d recommend you also install an WP-SMTP-Mail style plugin also, which might rectify the issue.

  10. @Gaya – Thanks, I’m glad you found it useful.

    @Japh – Thank you. I need to try the “Subscribe to Comments” plugin again – thanks for the reminder 😉

  11. Nice article, I had known there was a way to have WP include jQuery since I noticed it included twice on a WP build – once by me and the other by some plugin.

    Thanks for clearing up how to do this.

  12. Just a small note: in your 4th example you don’t need to call wp_enqueue_script('jquery'); separately. It will be added automatically as it’s listed as dependency. This is the case for all scripts WordPress knows about, either default or registered by themes/plugins.

  13. Hi Eric, nice post, re:jQuery conflicts, when you do have a plug-in which is messing with non-conflict mode that I have hard coded-what’s the best way around that sort of thing?

    Mess with the plug-in to make it comply or is there something else that can be done?

  14. Just started WP theming and stumbled across this article once I realized WP was loading its own jQuery files via plugins. That’s a huge performance/conflict impact when you don’t realize it and are loading jQuery on your own in a theme. I guess even if you’re just doing theming you still need to research all the plugin methods.

    Anyway, very good info. Got me going in the right direction… Thanks!

  15. Milan’s a bit harsh isn’t he…lol. However, he does have a point, even if his reasons are way off.

    I personally hate using plugins to solve, otherwise simple issues. With all that said, I’m using this plugin right now because I can’t find a way to get wp_enqueue_script() to stop appending a version number to the end of the script:
    ‘https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?ver=1.3.2’

    This query string at the end reduces the chances that the file is already cached on a user’s system.

  16. I was looking for this information so long. The most I need to know is “How To” using wp_enqueue_script() and I got it now 😉

  17. @Andrew – thanks for pointing that out.

    @JND – personally, I would modify the plugin, if possible, to get it working, then notify the author to fix it.

    @Kevin Lloyd – but this isn’t a plugin…Milan was suggesting the use of one instead of using the information I provided. You’re right about the query string / caching issue though 😉

  18. This post is priceless. Thank you so much for sharing this info. Finally can go back to coding 🙂

  19. Also this is the wrap I used for my plugin to get rid of all the errors.


    jQuery(function($){
    $.fn.extend({
    plugin_name: function( options ){
    ....
    }
    });
    });

    Sorry for the double post. 😉

  20. Pingback: Aliso the Geek

  21. Thanks for this post, I’ve referenced it several time since bookmarking it recently.

    I prefer to use Google’s hosted jQuery but do you know of a way to load WP’s copy of jQuery if for some reason the Google version doesn’t load?

    Thanks,
    John

  22. keep in mind that using wp_enqueue_script will cause jQuery to be loaded with every page, even pages that do not need jQuery.

  23. @ John:

    I like your idea, and I think something like this is needed somewhere in the footer:

    if (typeof jQuery == ‘undefined’) {
    // jQuery is not loaded :
    // document.open(‘local.jquery.path’);
    } else {
    // jQuery is loaded
    }

    for the part of loading the local copy I’m not sure.. refining needed here, but great post

  24. About “Hacking”: In the WordPress world, coding functions, using the APIs and writing plugins and themes are all considered “hacking”. Hacking is not bad, and it’s what you are supposed to do. The pop-culture reference to “hacking” is criminal behaivor black-hat hacking, and is different. There is nothing wrong with hacking WordPress.

  25. Thank you so much for this. I was beginning to pull my hair out trying to get WP, jQuery, and Superfish to play nicely together.

    I looked at a bunch of other sites and got no where. Luckily I found your tips to be very clear & exactly what I was looking for.

    Note, I also found https://themocracy.com/2010/01/more-wordpress-and-jquery/ to be helpful with the suggestion to define the location of template directory in functions.php using something like

    define(THEM_TEMPLATEURL, get_bloginfo('template_directory'));

  26. Pingback: 5 Cool Hacks and Tutorials Using WordPress and jQuery - WPConstructs.com

  27. Pingback: Using jQuery With WordPress: A Quick Crash Course and Performance Tips - WordPress MU and BuddyPress plugins, themes, support, tips and how to's

  28. Pingback: 10 Awesome Tutorials Combining WordPress And jQuery | wpCanyon

  29. I currently have two plugins calling Google Ajax. One is including in my header and is causing conflict with the other (my e-commerce shop).Anyone have any ideas how I could get around this without having to drop one of the plugins?

  30. Jquery is in use on my site for an accordion cascading menu, for a horizotal slider carousel, and for vertical carousel of images with text. And probably more uses than that…

    I notice that a number of these plug-ins use some of the same files and I get problems whether I pare down file redundancies, which I have tried, or if I use all of them that each plug-in calls for.

    When I get my vertical carousel working then my cascading menu stops even though my horizontal image carousel keeps on chugging.

    What are the tips for not only properly sequencing files but directing the relevant code functions to just the intended plug-ins?

    In other words, how can we target the plugin functions with only the parts of the code in these files that pertain to that plug-in, even if many base values and styles are being simultaneously computed and updated to make other animation actions occur with other plug-in actions?

    How can I make these multifarious scripts stay focused on the job at hand instead of negating or overwriting values and invalidating another plug-in?

    By the way, is there some sort of online js analyzer that can look at a WP page with multiple plug-in functions, find just the relevant code and outline only the code that is actually called for?

    I would love to reduce the jquery functions into one or two files that combine only the needed code.

  31. I’d like to use jquery and create a blog menu by myself, thanx for the first piece of info I need. Hope I’ll manage to create it.

  32. Great post, this sums up everything I wanted to know to optimise my jQuery use in WP, thanks Eric!

Comments are closed.

Scroll to Top