How to add jQuery to your WordPress site

The jQuery library is considered one of the famous JavaScript libraries. The primary goal of this library is to provide free and open source technology to website developers and designers to enable them to easily use the JavaScript language while designing the front-ends of websites.

Through this article, we will introduce you to the jQuery library, what its importance is, why we use it in website development, and how the jQuery library is dealt with in WordPress with or without plugins. We will also explain how you can use a different version of the jQuery library in WordPress instead of the current version that is built into it.

What is jQuery library?

jQuery is a popular JavaScript library that was created in 2006 by John Resge under the slogan (write less, do more) to make it easier for website developers and designers to use JavaScript on their websites. 

Instead of writing long, boring JavaScript code to achieve a specific task, you can use concise jQuery code that achieves the same task with fewer resources. However, in order to learn to use jQuery, it is necessary to have a basic knowledge of the JavaScript language and understand its programming logic. If you are not familiar enough with JavaScript, I advise you to read this article .

So in short, jQuery is a lightweight JavaScript library designed to make it easier to write JavaScript code for web browsers. It can be expressed in one sentence as (a way to write JavaScript more easily).

If you learn jQuery well, you will be able to add dynamic behavior and animation effects to static websites that cannot be achieved with HTML and CSS codes alone. Using easy and simple instructions.

Whether you want to navigate your web page smoothly, add animation effects, formatting, or specific actions to some page elements, call Ajax scripts, or other tasks, learning JQuery will make it easier for you to do this.

In order to learn JQuery, you need to know the concept of events that occur on elements, which are simply methods that express the behaviors that visitors perform while interacting with web pages, such as clicking the mouse button on an element on the page, or pressing a key on the keyboard. .

You must also know the concept of Actions , which represent the instructions that you will take or implement when a specific event occurs on one of the elements on the site (in short, it is the action that must be taken when the event occurs).

This scenario is expressed in jQuery within the front-end code of the pages as follows:

$(“element”).event_name(function()
{// action});

Note that JQuery instructions start with the symbol $, after which we specify the element on which we want to listen for events, in order to perform the action when the desired event occurs.
The previous phrase means, in short, (whenever an event occurs on an element, a specific action is executed).

To better illustrate the idea, let’s say, for example, that we want to write code that does the following:

When the user (clicks with the mouse) inside a specific menu item on the web page (menu-item-1), the color of another specific item on the page with the ID p2 will change to yellow.

To write the previous code in JavaScript, we must write the following: 

document.querySelector(‘#menu-item-1’).addEventListener(‘click’,function(){
document.getElementById(“p2”).style.color = “yellow”;
});

On the other hand, the previous task can be simplified and done using JQuery as follows: 

$(‘#menu-item-1’).click(function(){
$(“p2”).css(“background-color”, “yellow”);
});

Note that we’ve shortened the code and made the syntax much simpler and more understandable. The JavaScript function addEventListener has been replaced in the first code, which listens here on the click event that occurs when the user clicks once with the left mouse button on a specific menu item, which is menu-item-1. 

Instead, it was replaced in the second code with a click event in jQuery, and here we only needed to write one word after the item name menu-item-1.

From this simple example we can deduce the fundamental difference between using JavaScript and jQuery, especially when it comes to the simplicity in understanding and speed of execution that distinguishes code executed using the jQuery library from its JavaScript counterpart. 

Read also about the jQuery library in Hassoub Encyclopedia


Ways to load jQuery into websites

There are two general ways to load jQuery or any script into any website.

The first method: Download the jQuery script and upload it directly to the main site folder. For example, you can upload the jquery.js file to the js folder on your site, then you can copy the following code and paste it into the HTML header of the site pages.

<script src = “./ js / jquery.js”> </ script>

The second method : Read the jQuery script through the Content Delivery Network (CDN). After specifying the version that you want to upload to your site (for example, jQuery 3.x version), you can refer to it by writing the following code in the HTML header of the site pages:

If you want to use the official JQuery library, write the following code:

<script src=“https://code.jquery.com/jquery-3.4.1.min.js”>
</script>

If you want to use the GQuery library provided by Google, type the following:

<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js”>
</script>

After calling the library, you can start calling JQuery instructions, where the instructions are written similarly to writing JavaScript instructions within the <script> tag, as the general form of writing instructions is as follows:

<script>
$(#foo’)…
</script>

You can also save the instructions you want in a file with a .js extension, say its name, for example, my-jquery.js, and then call it via the file link. Here, there is no need to tag </script< within the file. Rather, the instructions (that begin with $) can be written directly in the file. . 

< script type= “text/javascript” src= “file link” >< /script >

Features of jQuery library

Although there are many JavaScript libraries, jQuery has gained great popularity for:

  • Lightweight: The small size of the jQuery library does not slow down applications and websites significantly, and you can also add it to your site through a Content Delivery Network (CDN) and provide it for loading on your site. 
  • Compatible with most browsers: The jQuery library works efficiently on all browsers, even old ones.
  • Open source : hence any developer can develop their own plugins using it.
  • Easy to learn: Developers can learn it in a short time compared to other JavaScript libraries, frameworks, and other programming technologies because it is short and concise. 
  • AJAX technology makes it easy to use without effort or long programming codes: AJAX is a technology that works asynchronously with the rest of the code on the site, and thus its content can be updated without having to update the entire page. 
  • Support: The JQuery library has excellent documentation where you can see a lot of useful information about everything in this library and learn how to use and install it. 

Using jQuery in WordPress

 WordPress comes with a version of the jQuery library built-in, which means you can use jQuery code directly without writing any call to the official library in the page code and making the various changes you want to apply to your site.

You can check this and make sure that jQuery is loaded by default in your WordPress site by viewing the source of any page on the site. 

You will notice a code similar to the following code

<script src=‘https://example.com/wp-includes/js/jquery/jquery.min.js?ver=3.6.0’ id=‘jquery-core-js’>
</script>

Of course, the version number varies depending on the version of WordPress for your site. This means that you can use jQuery code directly in your WordPress site.

But in reality, you should be aware that the jQuery built into WordPress itself is slightly different from the standard jQuery, as it is specific to WordPress and does not use the standard jQuery instructions that begin, as we explained, with the $ symbol.

The reason we can’t disable standard jQuery commands starting with a dollar sign $ in WordPress is to avoid conflicts with other JavaScript libraries available in WordPress as many JavaScript libraries use the dollar sign $ as a function or as a variable name. 

Perhaps the question that comes to your mind now is: How can I highlight jQuery directives in WordPress?

To solve this problem, the $ symbol in WordPress was replaced with the word jQuery to avoid conflicts with other libraries (it can be said that the word jQuery is an alias or alternative to the $ symbol in WordPress). 

Thus if we have the following standard code instructions in the JQuery standard library: 

/* Regular jQuery */
$(‘.hideable’).on(‘click’, function() {
$(this).hide();
})

The instructions will be written in the following format for compatibility with the WordPress jQuery library: 

/* Compatibility Mode */
jQuery(‘.hideable’).on(‘click’, function() {
jQuery(this).hide();
})

But typing jQuery multiple times in a text makes it harder to read and increases its size. So if you still want to use a dollar sign before every jQuery statement in WordPress as usual, there are several ways to get around this and make the $ sign work without conflict.

First method: If you want to write the code in the header of the page, then you can use the document’s ready function and wrap the standard code (Regular jQuery) within it as follows: 

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

Second method: If you want to write the code in the footer of the page (which is what you prefer to do in most cases), you can wrap the code in an anonymous function whose task is to convert $ to jQuery in the standard code (Regular jQuery) as follows: 

(function($) {
$(‘.hideable’).on(‘click’, function() {
$(this).hide();
})
})( jQuery );

Third method: Another simple way to avoid writing the word jQuery is to define a variable named $j or any other name you choose and pass the following value to it to prevent conflicts: 

var $j = jQuery.noConflict();

Now $j is now an alias for the jQuery function, then write the code as usual, replacing jQuery with $j (you will still be able to use jQuery as well as the new alias $j in the rest of the site)

The concept of compatibility mode (non-conflict) in WordPress

Compatibility Mode or No Conflict Mode in WordPress means that once jQuery code is loaded into WordPress, the site will enter a mode that helps prevent it from conflicting with any other JavaScript libraries you may be using on that site.

Actually noConflict mode means that the standard $ sign used in jQuery (and other JavaScript libraries) is unusable, and must be replaced with jQuery.

Note that the version of jQuery that ships with WordPress automatically calls the jQuery.noConflict method. But if you are loading a different version of jQuery or want to replace the jQuery keyword with a shorter code, you will need to call it manually.

This mode is activated before writing any jQuery code by writing the following line of code:

jQuery.noConflict();

So this call has many benefits, as it ensures that there is no conflict between the jQuery library and any other library in JavaScript, in addition to the fact that it enables the programmer to create a new symbol that is placed instead of the word jQuery, as we mentioned previously. 

<script>
var $wp = jQuery. noConflict () // Avoid conflict
jQuery(document).ready(function($){
$wp(‘tr[class=”acf-row”]’).change(function(){
$wp(‘.total input’).text(“wpar!”);
});
});
</script>

Ways to use jQuery on WordPress sites

After we learned about the ways to write jQuery instructions in a way that is compatible with WordPress, we move on to explain the ways to use jQuery with WordPress. We have two cases here:

  • Case 1: Use jQuery built into WordPress.
  • Second case: Download a standard version of jQuery and use it instead of the jQuery built into WordPress 

First: Use the jQuery library included in WordPress

You have two ways to use the jQuery library included in WordPress, either using ready-made plugins or manually through code. In the following paragraphs, we will explain these two methods to you and explain what is the difference between them and you can choose the method that suits you?

The first method: using WordPress plugins.

There are several plugins through which scripts and scripts can be added to WordPress. The Insert Headers and Footers plugin is considered one of the best free plugins through which you can add jQuery, JavaScript, or even CSS codes to your WordPress site easily.

 After installing and activating the plugin, you can go to the Settings tab within the WordPress control panel and specify the name of the plugin Insert Headers and Footers as follows:

A window will open for you containing three text boxes that enable you to write the code in one of the following positions on the page (Header/Footer/Body). You can place the codes customized for jQuery in the section you want to write in one of the current template files on your site, as shown in the image: 

Note:
Remember that the best practice is to call jQuery code, as with all JavaScript code, in the footer so that it loads at the end of the page and does not affect its loading speed.

The second method is to embed JQuery scripts in WordPress manually

When working with WordPress, it is not recommended to add jQuery scripts to your site pages in the traditional way using the <script> tag. To avoid conflicts and other potential problems, you will need to load jQuery using the following method: 

1-Create the text file in which you want to write instructions, and its extension must be js, for example new-jquery.js. And upload it to the template files on your site.

2- Browse the site files through one of the FTP programs , or by logging in to the hosting control panel Cpanel< and choose Filemanager< then select the root folder of your site public_html< then the wp-content folder< then themes< then enter the current template folder Installed as a default template on your site. Let the installed template be a newspaper template, for example.

3- Download your file new-jquery.js in the template folder (it is better to manage your files and put this file in a new subfolder inside the main folder of your template, and let the subfolder be called js)

Note: It is also a good idea to create a child template of the existing theme on your site and write instructions in it as this will ensure that your parent theme files remain intact if you update the parent theme.

5- Now you must link this new-jquery.js text file that contains the jQuery codes to the functions.php file of your site template. You will find the Functions.php file inside your site’s current theme folder.  

The functions.php file is considered one of the most important template files, as the programming information that was formulated inside it is executed directly as soon as the website is run on the browser. You can see a detailed explanation of this file in  our following article .

Now you have to tell the theme to register the new-jquery.js file and show it in its correct location. To do this we will use the ready-made function wp_enqueue_script() . This function fetches JQuery files (or any script file in general) from the path that is passed to it, and it helps WordPress know which file should be uploaded first by telling it when to upload a file, where to upload it, and what its dependencies are. 

This function adds scripts to be executed to a queue according to the Enqueueing principle, and is one of the most convenient ways for a CMS to add jQuery scripts or scripts in general to WordPress. It is a systematic way to load jQuery or Javascript codes in WordPress by knowing their dependencies. Through this function, WordPress provides a queue for each file added to the queue to ensure that everything is working correctly. 

You can load this function into Functions.php as shown in the following code, which loads the same new-jquery.js file on all pages of the site in the Footer section. 

<?php
if(!function_exists(‘wpc_load_assets’)){
function wpc_load_assets(){
wp_enqueue_script( ‘wpc_new_jquery’, $get_template_directory_uri( ) . ‘/’ .‘new-jquery.js’, array(‘jquery’),‘1.0.0’, true);
}
add_action(‘wp_enqueue_scripts’, ‘wpc_load_assets’);
}else{
// notify the admin
}
/*

Below we detail what we mean by each of the parameters passed to the wp_enqueue_script function.

wp_enqueue_script( $handle:string, $src:string, $deps:array, $ver:string|boolean|null, $in_footer:boolean )

$handle:string The distinguished name of the script we want to call.

$src:string is an optional parameter that represents the script path (required when we want to use an external script that is not self-build in WordPress)

$deps:array An array of dependencies owned by the script. 

$ver:string|boolean|null The version number of the script.

$in_footer:boolean is a boolean value that when we pass true to it, it means that the place to load the script is in the footer (because the script is loaded by default in the <head> section)

Read more: Learn how to properly embed CSS and JavaScript files into a WordPress theme

Second: Dealing with the standard jQuery library within WordPress

 If you want to use the standard jQuery version instead of the custom version of WordPress, then you can call the library via CDN instead of downloading the entire library on the site. 

To use a specific jQuery version instead of using the jQuery that WordPress provides itself, you must write the following code in the header.php file of the theme 

Read more: Learn about the basic structure and hierarchy of WordPress themes

Please make a backup copy of header.php before modifying it. After the backup, write the following code in the header.php file.

<?php
wp_deregister_script(‘jquery’);
wp_enqueue_script(‘jquery’, ‘https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js’, array(), ‘3.3.1’);
?>

The location of writing this code is below where WordPress jQuery is loaded and before the following code: 

<?php wp_head(); ?>
  • The first line in the above code (“wp_deregister_script(’jquery)” is a command to not read the jQuery that WordPress provides by default.
  • The second line, wp_enqueue_script, is interested in reading the new version of jQuery that we want to use on our WordPress site (here we passed the link to version 3.3.1), and you can write the URL for the appropriate version that you want to use on your site.

Instead of modifying the header file, you can add the following code to the functions.php file

if(!function_exists(‘wpc_redefine_assets’)){
function wpc_redefine_assets(){
wp_deregister_script(‘jquery’);
wp_register_script( ‘jquery’,‘https://code.jquery.com/jquery-3.6.0.js’, [], ‘3.6.0’, false );
}
add_action( ‘wp_enqueue_scripts’, ‘wpc_redefine_assets’ );
}

As we mentioned previously, WordPress comes with a specific version of the jQuery library, and a different version of the jQuery library can be used, but this leads to a conflict in many of the features granted by the jQuery library, and the reason is that there are two versions of jQuery.

For this reason, the solution to this problem was found by using wp_deregister_script() to deregister WordPress jQuery and then include the jQuery version you want to add as shown in the previous code.

Then, JQuery codes can be written in the same ways as we explained previously (through plugins or manually by modifying template files).

Conclusion

In today’s article, we provided an overview of the JQuery library, which is considered one of the most famous Javascript libraries. We also explained its importance and how to include it in a WordPress site in various ways, whether through plugins or through manual code, and we explained how to use the library included with WordPress independently or use another standard library. 

We explained the concept of deconfliction mode, which aims to help ensure that there are no compatibility issues between jQuery and other JavaScript libraries loaded in WordPress.

Finally, we remind you that gaining skill in how to deal with jQuery will make the work you do easier and better, so do not hesitate to try it on your site and learn about the aesthetic effects it provides you, which cannot be created using HTML or CSS alone to distinguish the external appearance of your site.

Avatar photo
I am a young man who has been working in WordPress and e-marketing for 10 years. I would like to share my experience with you so that we can become professional in WordPress I will be happy to share the experience with you.