In order to use the wonderful jQuery library with your wordpress installation you could simply grab a copy put it on your server and link to it. However this could lead to trouble, when plugins need to use the jQuery library they will try to load it as well causing script collisions.
A better way or as the wordpress codec says a safer way to use the jQuery libraries or any of the included scripts is to use wp_register_script
or wp_enqueue_script
.
WordPress comes loaded with several libraries and scripts for your enjoyment, including:
- Scriptalicious
- jQuery
- Prototype
- Thickbox
- jQuery UI
The easiest way to load the jQuery library for would be to add the following code before the wp_head()
function,
wp_enqueue_script('jquery');
It’s important to note that the wordpress loads the internal version of the jQuery library in “no-conflict” mode which means the “$” shortcut will not work. You could use “jQuery” instead of “$”, however if you really want to use that dollar sign then in your jQuery scripts use the following code.
jQuery(document).ready(function($) {
// do jQuery stuff using $
});
You can also specify the source of the script if it is not included with wordpress and load dependencies using wp_enqueue_script
, the path to the script should be relative to the root directory of wordpress. The following example loads candy.js
which depends on “scriptalicious” and “scriptalicious-slider”.
wp_enqueue_script('candy', WP_CONTENT_URL. '/themes/name-of-theme/js/candy.js', array('scriptalicious, scriptalicious-slider'), false, true);
The first paramenter is the script name, the second is the path to the script, the third parameter array()
will load the files that candy.js
needs. The names in this array are not the filenames but rather the handles, these will be loaded before candy.js
After the dependencies parameter comes the version option, it’s a string specifying the version number of the script used if there are more than one version of the script.
The last parameter is the wp_enqueue()
function is an option to load your script wherever the wp_footer()
hook is located, it should be in the, uh —footer.
If this post helps you better understand the wp_enqueue function, let me know in the comments below.