Adding jQuery to WordPress

You could add your custom jQuery to WordPress by using the script tag in your head template, but this method can cause conflicts with JavaScript in other WordPress plugins.

Instead, use the wp_enqueue_script, the WordPress-friendly method. You will need direct access to your WordPress files.

  1. Go into wp-content/plugins, and create a new javascript folder.
  2. In this folder, place your .js file.
  3. In header.php, before <?php wp_head(); ?>, place this:
<?php
wp_enqueue_script('custom',
'/' . PLUGINDIR . '/javascript/yourscript.js',
array('jquery'),
'1.0' );
?>

That’s it. You don’t need to do anything additional to include the jQuery library, since it’s specified as in the array as a file that your script is dependent upon. In place of ‘jquery’ you can use Scriptaculous, jQuery UI Tabs, or any number of libraries that are built into WordPress.

Those libraries, as well as additional information about the wp_enqueue_script can be found at codex.wordpress.org/Function_Reference/wp_enqueue_script.

According to the codex, this script can’t be placed above <?php wp_head(); ?>, but I’ve found that on the contrary, it works ONLY when placed above it. This same page of the codex also says that ‘$’ can be used instead of ‘jQuery’ inside the document ready function, which is also currently not accurate.

In other words, where you would use ‘$’ in your jQuery function, you MUST use ‘jQuery’ for every instance, not just in the document ready function. Feel free to test this with your own script; I’m not sure why the Codex is wrong on these points.

This entry was posted in WordPress, jQuery. Bookmark the permalink.

3 Responses to Adding jQuery to WordPress

  1. Thanks very much for this useful piece of text.

  2. Алёна says:

    Ну и чё с ними делать… Меня достали на моём блоге я устала вычищать…

  3. Hey good looking blog but it is a bit weird looking in my K-meleon browser. Looks great besides that!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>