How to use jQuery in WordPress

jQueryOn a standalone (non-WordPress) project you’d import the jQuery library in the head tag, then call a jQuery function towards the bottom of your file.

This approach isn’t working in WordPress.

Since jQuery and many other useful libraries are already part of WordPress, there’s no need to link to your own copy. Instead, you need to “enqueue” such scripts before the closing head tag (and before wp_head() is called). This is done in your theme’s header.php file:

wp_enqueue_script("jquery");

Every additional library must be called separately, such as jQuery UI components.

Then in your footer.php file, just before the call to wp_footer(), trigger your script like this:

Note that the usual $(document).ready(function() or $function() will not work in WordPress.

Thanks to Joseph Lowery for this tip.

For a full list of which scripts you can enqueue, check out this article from the WordPress Codex.

Full Working Example

Imagine you want to call a simple JavaScript alert in your project. Let’s see how we can call that from within WordPress.

In your main plugin file, add a function that sets up and enqueues your script. In this example our script file is called “test.js” and resides in the main directory of our plugin:

 function guru_header_test () { 
	 // load our JS file
	 wp_enqueue_script ('jquery');
	 $testScript = plugins_url ('test.js', __FILE__);
	 wp_enqueue_script ('header-test-script', $testScript);
 }
 add_action ('init', 'guru_header_test');

First we enqueue jQuery which ships with WordPress. Next we grab a reference to our own file and store it in a variable, using the plugins_url() function. Then we enqueue our script by giving it a handle and passing in the reference to the file.

In the last line we add this as an action early on in the process using the init hook. Now our jQuery script is loading on every page (something to be aware of).

Our jQuery code can only be executed when the document is ready, so it won’t work by just adding one line to our test.js file. Instead, we need to wrap our code into the document.ready function like so:

// do this on document.ready
jQuery(document).ready(function() {
    alert('Hello!');
});

Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or drawing on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.