How To Properly Add jQuery Scripts To WordPress

WordPress has been in our lives for over 16 years, yet the method of adding scripts to themes and plugins still remains a mystery for many developers. In this article we finally put the confusion to rest.

Since it’s one of the most commonly used Javascript libraries, today we’re discussing how to add simple jQuery scripts to your WordPress themes or plugins.

But first…

About jQuery’s Compatibility Mode

Before we start attaching scripts to WordPress, it’s important to understand jQuery’s compatibility mode.

As you’re probably aware, WordPress comes pre-loaded with jQuery, which you can use with your code.

WordPress’ jQuery also has a “compatibility mode,” which is a mechanism for avoiding conflicts with other language libraries.

Part of this defense mechanism means you cannot use the $ sign directly as you might in other projects.

Instead, when writing jQuery for WordPress you need to use jQuery.

Check out the code below for an example:

/* Regular jQuery */
$('.hideable').on('click', function() {

/* Compatibility Mode */
jQuery('.hideable').on('click', function() {

The problem is, writing jQuery a gazillion times takes longer, makes it harder to read, and can bloat your script.

The good news?

With a few modifications you can go back to using our lovely little dollar sign once again.

BTW, if you’re new to jQuery, the $ sign is just an alias to jQuery(), then an alias to a function.

The basic structure looks like this: $(selector).action(). The dollar sign defines jQuery… the “(selector)” queries or finds HTML elements… and finally the “jQuery action()” is the action to be performed on the elements.

Back to how we can get around our compatibility issue… here are a couple of viable options:

1.Enter jQuery Stealth Mode

The first way to get around compatibility mode is to get stealthy with your code.

For example, if you’re loading your script in the footer, you can wrap your code in an anonymous function, which will map jQuery to $.

Like in the example below:

Leave a Reply

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