How to use jQuery in WordPress

On 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:

1

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.

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:

1

2

3

4

5

6

7

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:

1

2

3

4

// do this on document.ready

jQuery(document).ready(function(){

alert('Hello!');

});

Share this:

Related

About Jay Versluis

Jay is a medical miracle known as a Super Survivor. He runs two YouTube channels, five websites and several podcast feeds. To see what else he's up to, and to support him on his mission to make the world a better place, check out his Patreon Campaign.