If you have ever worked with jQuery, you will know how powerful it is. Besides cutting down the amount of javascript you write you also have access to tons of cool plugins written by enthusiastic developer around the world that do a lot of great functionality for you.

Using jQuery with WordPress is pretty much the same as using it on any other project except there is a wrong way and a right way of adding it your theme.

Wrong way

If this is the first time you are adding jQuery to your theme you’ll probably do something like this:

1
<script src="<?php bloginfo('template_url');?>/script/jquery.js" type="text/javascript"></script>

This method is wrong, or at least it is not the preferred method.

The right way

WordPress has a method called wp_enqueue_script which is used to load scripts that you need in your theme. So to include jQuery you’d do the following before you call the wp_head method:

1
<?php wp_enqueue_script('jquery'); ?>

This will then load the version of jQuery in the wp-includes/js/jquery folder of your wordpress installation. Pretty simple huh?

Loading jQuery from a CDN

Calling jQuery from a CDN requires two extra lines of code, one is to call wp_deregister_script which will remove the default handle for jQuery and then you call wp_register_script which will create a new handle for jQuery and call it from the address you specified. So at the end of the day the code will look like this:

1
2
3
4
5
<?php
wp_deregister_script('jquery'); // remove handle to jQuery
wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js');
wp_enqueue_script('jquery');
?>

And there you go, now you know how to add jQuery properly to your wordpress theme. Happy coding!

Filed under: Help jQuery Wordpress