How to use JavaScript in WordPress

How to use JavaScript in WordPress

When I first started making websites in WordPress I will admit when it came to JavaScript I did it all wrong … sort of. One of my favourite things with WordPress is how to integrate JavaScript with WordPress. I am going to explain how to implement JavaScript properly with WordPress using some functions.

The Beginners Way to Implement JavaScript

So one of the biggest mistakes I made was just adding the JavaScript to the header.php file like below.

<script type="text/javascript" src="<?php echo get_stylesheet_directory_uri(); ?>/assets/js/jquery.js"></script> 
<script type="text/javascript" src="<?php echo get_stylesheet_directory_uri(); ?>/assets/js/init.js"></script> 

This is wrong for two reasons.
Firstly Jquery comes with WordPress(I will explain later in the tutorial) so you don’t need to copy JQuery into a file.
Secondly the init.js(assuming that the file uses JQuery) is reliant on JQuery so if there is something goes wrong with the file it might break your script.

The Proper Way to Implement JavaScript

We are going to use a function called wp_register_script and wp_enqueue_script
Firstly we are going to use the action init with wp_register_script to register the script

function cm_register_script() {
   wp_register_script('init.js', get_stylesheet_directory_uri() . '/assets/js/init.js', array('jquery'), '1.0', true);
}
add_action('init', 'cm_register_script', 999, 0);

What wp_register_script does is as you guess registers your script to be used in WordPress but before I show you how to call the script lets go through the parameters used.

  • handle: This is the name used to be called with wp_enqueue_script
  • src: The source of the script
  • deps: This is an array which the script relies on. So in the above script we are saying that this script needs jQuery and if it has not already been loaded, load the jQuery script when this script is called.
  • vers: This is used for caching purposes. If you don’t use add this the current version of WordPress is added
  • footer: A Booleen on wheter the script should be loaded in the footer. The default is false

But before we go any further I want to explain there are tonnes of scripts and JavaScript that come with WordPress such as JQuery, ColorPicker, Scriptaculous. This is very useful as we don’t have to download and update the scripts.

So to call the scripts we use wp_enqueue_script with the action wp_head.

function cm_add_scripts_to_footer(){
    wp_enqueue_script('init.js');
}
add_action('wp_footer', 'cm_add_scripts_to_footer', 10, 0);

Alternately we can don’t have to register the script and add the same additional parameter to wp_enqueue_script to file as follow.

    wp_enqueue_script( 'jquery' );
    wp_enqueue_script('init.js', get_stylesheet_directory_uri() . '/assets/js/init.js', array('jquery'), '1.0', true);

The reason why we might register script above is so it can be used in multiple files.

We can also remove a registered script. This might be useful if the site needs an older version of JQuery. You can remove the script and register an older version using wp_deregister_script

 function cm_register_jquery(){
    wp_deregister_script('jquery');
    wp_register_script('jquery'. get_stylesheet_directory_uri() . '/assets/js/jquery');
}
add_action('init', 'cm_register_jquery',10, 0);

JQuery

It is important to note that the JQuery used by WordPress is JQuery noConflict.This is to prevent problems with other JavaScript libraries. So if we were using JQuery in init.js file it would look something like this:

$(document).ready(function(){
  /* Code*/
}); 

wp_localize_script

This function I find this invaluable for error handling and adding other data for JavaScript.

So if you were validating a multi language contact form with JavaScript your error messages need to be translated. This is how you achieve this.

function cm_register_script() {
    cm_add_scripts_to_footer(){
    wp_enqueue_script('init.js');
    wp_localize_script( 'init.js', 'ErrorMsg', array(
            'errRequired' => __("This is required", "Theme/Plugin Name"),
            'errEmail' => __("A valid email is required", "Theme/Plugin Name")
    ));
}
add_action('wp_footer', 'cm_add_scripts_to_footer', 10, 0);

wp_localize_script is called once init.js is loaded. If you view the source of your page you will see the messages have been added as CDATA. There are 3 parameters to wp_localize script.

  • handle: The name of the JavaScript file which calls the script.
  • object name: The object name used for JavaScript (see below)
  • data: An array of data. The key is the object name used for JavaScript

So if I wanted to add a error message I do the following:

JQuery(document).ready(function($){
    $requiredErrorMsg = ErrorMsg.errRequired;
    $emailErrorMsg = ErrorMsg.errEmail;
});

So as you can see I use the object name of the script and the key(object name) in the array to get a specific message.

Please leave a comment below on any other useful functions/snippets to with JavaScript and WordPress or if you have any questions about the content above.

2 ResponsesSubscibe to the Comments FeedAdd Comment

  1. Smithe416 wrote on

    I’ve been absent for a while, but now I remember why I used to love this site. Thank you, I’ll try and check back more frequently. How frequently you update your site? dfgdgkdgeeedbdeb

Leave a Reply

css.php