webappguides
Create Wordpress Theme From Scratch! Build Your Own

How to add JavaScript to WordPress in the functions.php

webapps log

webapps Lab
January 25, 2021
ThemeFunctions

Adding functionality and events in WordPress themes may require to use a javascript.

Incorrectly adding the script can cause a javascript to fail to work.

Because

WordPress has its own proper way to include the js file correctly in the theme.

In most cases, you can add some functions in the functions.php file to add the javascript codes.

In this post, you will find the WordPress functions to register javascript properly.

These functions allow you to put

  1. external javascript
  2. internal javascript
  3. javascript to a specific page.

And the function that I’m going to demonstrate can add any javascript source without a plugin.

Of course this you will add javascript to WordPress in the functions.php in many ways.

Let us start.

Shortcode 1

To avoid incorrect ways of adding js scripts in WordPress, functions.php should contain a function that enqueues javascript.

The function registers  and enqueue the script using these two functions.

  1. wp_register_script
  2. wp_enqueue_scripts

And this is how to implement wp_register_script and wp_enqueue_scripts in the given function.

1.function customJavascript(){

2.wp_register_script("customJS",get_template_directory_uri()."/js/customjs.js");

3.wp_enqueue_scripts("customJS");

4.}

5.add_action('wp_enqueue_scripts','customJavascript');

Codes Explanation

The path source of a javascript file that you want to add to the page must be registered.

Without registering a script path the WordPress framework may fail to load the script.

The appropriate function that will register the script to be enqueued later  is wp_register_script.

The path registration process takes two arguments on this example.

The first parameter is $handler, representing the name of the javascript file (any desired name is acceptable).

The script name in this code is customJS

The second parameter is the string $path representing the path directory of the javascript file.

The get_template_directory_uri, javascript file directory and the javascript file name create a string for the second argument.

get_template_directory_uri returns the path of the theme root directory.

If the script lives in another folder in the root folder, get_template_directory_uri should be appended with the name of the js folder.

In my case, the javascript folder is js, and when you append start with a slash like this.

get_template_directory_uri()."/js/customjs.js

Line-3 uses wp_enqueue_script to include the registered script on the page.

wp_enqueue_script should receive the name used to register a javascript in wp_register_script

Line-5 calls add_action hook to include the script in the header.

There is another way to add javascript in function.php without wp_register_script

Here it is.

shortcode 2

1.function customJavascript(){

2.wp_enqueue_scripts("customJS",get_template_directory_uri()."/js/customjs.js");

3.}

4.add_action('wp_enqueue_scripts','customJavascript');

internal javascript

If you know the correct path of the javascript file, you can employ the get_template_directory_uri function to set the script in the functions.php file.

Though, you should append the function with a directory where there is a required script file.

For example,

Assume the theme folder where javascript files reside has been named to js-directory.

The folder name will append with get_template_directory_uri to form a string of a javascript source.

That path represents an internal javascript file.

This how to set a local path to add the internal javascript to a page.

$customScriptSrc = get_template_directory_uri().’/js-directory/customOne.js’

After setting the script folder the two functions can be called to add internal javascript.

This how to do it.

1.function internalCustomJavascript(){

2.$customScriptSrc = get_template_directory_uri().’/js-directory/customOne.js’

3.wp_register_script("customJS",$customScriptSrc );

4.wp_enqueue_scripts("customJS");

5.}

6.add_action('wp_enqueue_scripts','internalCustomJavascript');

or

1.function customJavascript(){

$customScriptSrc = get_template_directory_uri().’/js-directory/customOne.js’

2.wp_enqueue_scripts("customJS",$customScriptSrc);

3.}

4.add_action('wp_enqueue_scripts','customJavascript');

The question is, how to include the script that is hosted in external server?

Here is the answer.

Adding external javascript

There is a different approach when the theme uses the javascript library that is hosted in another server or content delivery network.

To add external javascript codes, wp_register_script must receive a URL (link) of the script.

Hence, a theme directory is not needed for this case.

This shortcode adds a reactjs library using react CDN links.

function externalJS(){

$reactLib=”https://unpkg.com/react@17/umd/react.development.js”;

3.wp_register_script("externalJS",$reactLib );

4.wp_enqueue_scripts("externalJS");

}

4.add_action('wp_enqueue_scripts','externalJS');

Alternative

function externalJS(){

$reactLib=”https://unpkg.com/react@17/umd/react.development.js”;

4.wp_enqueue_scripts("externalJS",$reactLib);

}

4.add_action('wp_enqueue_scripts','externalJS');

The setup of the previous shortcodes passes two required parameters.

Athough, wp_register_script can receive six parameters.

Adding few parameters limits the extra feature to include in the script.

You can specify extra settings for the script if you know the work of each parameter of wp_register_script and  wp_enqueue_scripts.

Let’s see how to add extra data by setting other parameters.

wp_register_script parameters

The first two parameters of wp_register_script are the $hanlde representing a unique name and $src representing a path of a javascript file.

But forget these parameters since you have used them in the first examples.

Instead let’s focus on a third, fourth, and fifth parameter.

The third argument is $depth.

$depth

$depth is an array string representing the names of registered handles (names of scripts).

This array setting helps to pass the addition registered javascript files to a page  in function.php

For example.

Let say you have registered several custom js files before, the script for the slider, carousel, and ajax as an example.

The recommended scripts are the ones on which a current custom script depends on like ajax or jquery libraries,

This is how to include several registered handles.

function addSeveralScripts( ){

wp_register_script("nameOfScript", get_template_directory_uri(). "/js/custom.js" ,array("ajax","slider", "carousel"));

wp_enqueue_scripts("nameOfScript");

}

add_action('wp_enqueue_scripts', 'addSeveralScripts');

$ver

This variable enables to assign a version number to a script to register.

In case a javascript the page is using will several version and frequent updates, this variable helps to register the version numbers of the script.

In fact, $ver can be a boolean, null, or a string.

If you don’t want to add the version number leave $ver as an empty parameter since its default value is null.

But if you want the same version to be the same, just set a $ver to false.

Otherwise, give the fourth parameter of wp_register_script a version number like this.

function addScriptsVersionNumber( ){

wp_register_script("nameOfScript", get_template_directory_uri(). "/js/custom.js" ,array("ajax","slider", "carousel"),"1.1.5");

wp_enqueue_scripts("nameOfScript");

}

add_action('wp_enqueue_scripts', 'addScriptsVersionNumber');

$in_footer

It is a boolean variable that specifies the section of the page in which the script will appear.

Normally, javascript scripts tag are placed in the head.

But the tags can be written before the </body>.

Hence, $in_footer gives the option of where to put the script.

setting $in_footer to true places the tag before the <body> closing tag.

Otherwise, the script tag is going to appear in the head

Now let’s see the parameters that enqueue a script.

wp_enqueue_scripts parameters

All the parameters of wp_register_script and wp_enqueue_scripts are the same.

So, if you know the wp_register_script variables it is enough.

Although there are additional methods that wp_enqueue_script uses to add attributes to a script tag.

Check it on WordPress and how to remove style.css

wp_enqueue_scripts in add_action function

If you look at shortcodes examples, you will add_action function is being called.

Actually, add_action executes the function that adds javascript.

Here, it only receives two parameters.

  1. The action hook name which is wp_enqueue_scripts
  2. The name of the function to execute.

Without add_action the function in the functions.php file won’t add js file scripts to a page.

Conclusion

The key function to add javascript properly in WordPress is wp_enqueue_scripts.

Although, the wp_register_script simplifies the work of wp_enqueue_script.

In a simple word when you register the js wp_enqueue_script receives the name of registered javascript only.

And if you ignore wp_register_script the wp_enqueue_script should pass the name of a script and the javascript path.

All in all, these two methods are working fine on my side and I believe they can work for you too.

Learn how to build SEO friendly WordPress theme from scratch before adding javascript.