Skip to Main Content

How to properly add jQuery code to WordPress

Divi: the easiest WordPress theme to use

Divi: The best WordPress theme of all time!

With over 901.000 downloads, Divi is the most popular WordPress theme in the world. It is complete, easy to use and comes with more than 62 free templates. [Recommended]

WordPress has been part of our lives for over 16 years, but the method of adding scripts to themes and plugins remains a mystery to many developers. In this article, we've finally put an end to the confusion.

Since this is one of the most used JavaScript libraries, today we are discussing how to add jQuery scripts to your WordPress themes or plugins.

About jQuery compatibility mode

Before you start adding scripts to WordPress, it's important to understand the compatibility mode of jQuery.

As you probably know, WordPress comes with jQuery already included.

The version of jQuery on WordPress also has a " compatibility mode Which is a mechanism to avoid conflicts with other javascript libraries.

Part of this defense mechanism means that you you can not use the $sign directly as you would in other projects.

Instead, when writing jQuery code for WordPress, you should use jQuery.

Here's an example of that code:

/ * JQuery régulier * /
$ ( '.hideable' ).on( 'click' , function () {
$ ( this ).hide();
})

/ * Mode de compatibilité * /
jQuery ( '.hideable' ).on( 'click' , function () {
jQuery( this ).hide();
})

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

The good news?

With a few modifications, you can again use our cute little dollar symbol.

By the way, if you are new to jQuery , the $ sign is just an alias for jQuery (), then an alias for a function.

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

Back to how we can work around our compatibility problem… here are some viable options:

1.Enter jQuery stealth mode

The first way to get around compatibility mode is to sneak into the code.

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

As in the example below:

Easily create your website with Elementor

Elementor allows you to easily create any website design with a professional look. Stop paying expensive for what you can do yourself. [Free]

( fonction ( $ ) {
$ ( '.hideable' ).on( 'click' , function () {
$ ( this ).hide();
})
}) (jQuery);

If you want to add your script in the header (which you should avoid if possible, more on that below), you can wrap everything in a document-ready function, passing the $along the way.

jQuery( document ).ready( function( $ ) {
$ ( '.hideable' ).on( 'click' , function () {
$ ( this ).hide();
})
});

2. Enter "No Conflict" mode

Another easy way to avoid spelling out jQuery is to switch to mode "Conflict free" and use a different shortcut.

In that case: $jinstead of the default $.

All you have to do is declare it at the top of your script:var $j = jQuery.noConflict();

Okay, now you know more about writing valid jQuery code for WordPress, let's add it to our website.

How to add jQuery scripts to WordPress

One of the easiest ways to add jQuery scripts to WordPress is through a process called 'setting waiting line ».

For a classic HTML website, we would use the  <link> item to add scripts. WordPress ends up doing the same, but we'll use special WP functions to achieve this.

In this way, it manages all of our dependencies for us (thanks WP!).

If you are working on a theme, you can use the function  wp_enqueue_script() in your  functions.php file.

Here's what it looks like:

function my_theme_scripts () {
wp_enqueue_script('mon-grand-script', get_template_directory_uri(). '/js/my-great-script.js', array('jquery'), '1.0.0', true);
}
add_action('wp_enqueue_scripts', 'my_theme_scripts');

This function takes five arguments:

  1. $ handle - a unique handle that you can use to refer to the script.
  2. $ src - the location of the script file.
  3. $ deps - specifies an array of dependencies.
  4. $ ver - the version number of your script.
  5. $ in_footer - lets WordPress know where to put the script.

* One thing to note  $in_footer means that by default scripts will be loaded in the header.

This is bad practice and can slow down your site considerably. Therefore, if you want to place your script in the footer, make sure this parameter is set to true.

Are you looking for the best WordPress themes and plugins?

Download the best plugins and WordPress themes on Envato and easily create your website. Already more than 49.720.000 downloads. [EXCLUSIVE]

Adding scripts to the WordPress administrator

You can also add scripts to the administrator. The functions used are exactly the same, you just need to use a different hook.

For example:

function my_admin_scripts () {
wp_enqueue_script ('my-great-script', plugin_dir_url (__FILE__). '/js/my-great-script.js', array ('jquery'), '1.0.0', true);
}
add_action ('admin_enqueue_scripts', 'my_admin_scripts');

Instead of logging in, wp_enqueue_scriptswe must use admin_enqueue_scripts.

How to unsubscribe jQuery from WordPress

But what if you want to use a different version of jQuery than the one preloaded by WordPress?

You can queue it… but that means there will be two versions of jQuery on the page.

To avoid this, we need to unregister the version of WP.

Here's what it looks like:

// includes custom jQuery
shapeSpace_include_custom_jquery () function {

wp_deregister_script ('jquery');
wp_enqueue_script(
   'jquery', 
   'https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js', 
   array(), 
   null, 
   true);
}
 add_action ('wp_enqueue_scripts', 'shapeSpace_include_custom_jquery');

It's as easy as using the  wp_deregister_script () for unregister jQuery from WP, then including the jQuery script you want to add.

In the example above, we used the jQuery library hosted by Google , but you will obviously replace it with the URL of your own script.

Shouldn't you save scripts before queuing them?

If you want to load your scripts as needed instead of loading them directly into your pages - you can save the script earlier.

For example, on  wp_loaded:

add_action ('wp_loaded', 'register_all_scripts');
fonction register_all_scripts () {
wp_register_script (…);
}

Once you've done that, you can then queue the scripts when you need them:

add_action ('wp_enqueue_scripts', 'enqueue_front_scripts');
add_action ('admin_enqueue_scripts', 'enqueue_back_scripts');

Remember to use the same names to avoid colliding with other scripts.

Using conditional tags

Use conditional tags to load your scripts only when needed.

This is used more often in administration, where you want to use a script on a specific page only (and not in the entire administration). It also saves bandwidth and processing time which means faster load times for your website.

Take a look at the documentation of queuing scripts  in the WordPress Codex for more information.

Easily create your Online Store

Download free WooCommerce, the best e-commerce plugins to sell your physical and digital products on WordPress. [Recommended]

Add jQuery to WordPress using plugins

The WP plugins directory also contains many interesting plugins that you can use to insert scripts into your WordPress publications, pages or themes.

Here are some examples of well-known JavaScript / jQuery plugins: advanced custom fields , Simple custom CSS and JS , script styles n et resource cleaning.

Create your own jQuery project

A better understanding of jQuery will only make your work more impactful. Whether for your own website or for client projects.

jQuery is well known for its simplicity, and as you (hopefully) learned in this article, adding simple jQuery scripts to WordPress is easy as pie once you know how.

Yes, there is a bit of overhead compared to using vanilla HTML, but there is also the added benefit of dependency management and clarity.

Not only that, by using little tricks like bypassing jQuery WP's default compatibility, you'll save yourself a lot of time, effort, and bloated code.

This article features 0 comments

Leave a comment

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

This site uses Akismet to reduce unwanted. Learn more about how your comments data is used.

Back To Top
2 shares
Share2
tweet
Save