According to the latest tech surveys, JavaScript is by far the most popular programming language in the world. As you’ve probably already know, JS runs on your browser and adds life and interactivity on the otherwise dull static web pages.
You can use JavaScript to modify document elements or add extra functionality to them. You can modify the layout, design or behavior of a WordPress theme or plugin. You can even play media, add animations or user tracking, embed social sharing functionality and insert scripts for connecting to third-party APIs.
Closely following JavaScript’s popularity, and built on top of it, jQuery is one of the most commonly used libraries throughout the web. With its simple syntax and its vast array of helper functions, it makes the process of adding interactivity and special effects on web pages a breeze.
Thus, it makes sense that one of the most common questions that arise in online forums and search queries alike, is how can one embed a JavaScript library or add some custom JavaScript or jQuery code on their WordPress site.
In this article, we are going to guide you through almost every single way of adding JavaScript on your WordPress pages, in order to help you determine which one is best suited for your case.
Table of Contents
Fundamentals
Add JS using Gutenberg
Add JS using the Classic Editor
Add JS in the Head and Footer Sections
Registering and Enqueuing Scripts
Adding Inline JavaScript
Adding Localized Data: How to pass PHP data to JavaScript
Add JS using Plugins
Add JS using the WPBakery Page Builder
Overview – Comparison Table
Troubleshooting
Fundamentals
Requirements and Use Cases
Before moving on and introducing all the available methods of adding JavaScript to your WordPress site, we need to briefly describe the various options, requirements and use cases of these methods. At the end of this post, you will find a table that contains each method’s available options.
Site-wide or specific post/page:
– Add JavaScript on a site-wide basis (across all pages of a website): For example, adding a Google Analytics script to track all web pages.
– Add JavaScript on specific posts or pages, e.g. Adding a booking form on a single page. This way, you are injecting the code only where it belongs, without overloading the rest of the site with unnecessary HTTPS requests or code execution.
Page Section:
– Add JavaScript on the <head> section of web page(s). For example, when you need to load a JS library that will be used by subsequent scripts.
– Add JavaScript before the closing body tag (</body>) of web page(s), if your script requires access to rendered document elements and you don’t want to block web page rendering.
Custom or External Script:
– Add an external/third-party JavaScript file. An external script is loaded using the <script> tag along with the src attribute:<script src="https://cdnjs.com/library.js"></script>
– Add inline (custom) JavaScript code inside the <script> tags:<script> console.log("JS Code goes here!"); </script>
With or without a Plugin:
– Add JavaScript using native WordPress functionality.
– Add JavaScript using a popular WP Plugin.
Adding JavaScript using the Editor:
– Gutenberg Editor.
– Classic Editor.
– Third-party Page Builder.
Word of Caution
Although you can add JavaScript code by modifying the header.php and/or footer.php theme files, either directly on the parent theme or by overriding these template files in the child theme folder, when doing so, you are running the risk of losing the changes on your next theme update or breaking your parent theme’s code functionality. This practice is discouraged and should be avoided. Therefore, we are omitting such methods from the current list.
Add JS using the Gutenberg Editor
Specific Posts, Pages or Custom Post Types
One of the simplest ways to add JavaScript to a WordPress post, page or custom post type, is by using the Custom HTML Block found in the Gutenberg Editor.
Simply, open a Post, Page or Custom Post Type, add a Custom HTML Gutenberg Block and add your JS code inside a <script> tag.
You can embed your custom JS code inside the opening and closing <script> tags, or you can load an external JS library by adding a URL in the src attribute of the <script src=”URL”> tag.
If you prefer to place your code in an external script file or host third-party JavaScript code on your own server, you can upload the files to your child theme folder ( e.g. /wp-content/themes/child-theme/ ) or the /wp-content/uploads folder and place the appropriate URL in your script tag’s src attribute. For example, if your domain is happyplace.com and you have placed your myscript.js file in the /wp-content/uploads/ folder, you will need to use the https://happyplace.com/wp-content/uploads/myscript.js as your script’s src attribute value.
Add JS using the Classic Editor
Specific Posts, Pages or Custom Post Types
If you have switched to the Classic Editor, your options for embedding JavaScript code on a specific Post or Page, are rather limited. The only way you can add <script> tags into your content, is by switching to Text Mode and edit using an Administrator or Editor Role. This can turn out to be quite tricky, especially when working with rich content, so caution must be taken when switching from Visual to Text Mode and vice versa. For a much easier option, you can check out the Plugin methods found further down.
Adding JS in the
Head & Footer Sections
Using the wp_head & wp_footer Hooks
One of the most convenient ways of extending the functionality of WordPress is by using the Action Hooks. We can perform various actions at different stages of the rendering lifecycle of each WP page. For example, we can use the wp_head action hook to inject custom markup inside the template’s head tag section.
To insert our script tags inside the <head></head> section, we need to edit the functions.phpfile of our child theme and add the following code:
CAUTION: functions.php acts much like a plugin and can be used to add features and extend the functionality of WordPress. As certain changes or typos in this file may result in fatal PHP errors, always create a backup of your functions.php before actually editing the file, in order to restore to the original version in case something breaks.
function ple_hook_javascript() {
?>
<script>
// Your JavaScript code goes here...
</script>
<?php
}
add_action( 'wp_head', 'ple_hook_javascript' );
The code above will inject the script on all Posts and Pages. In case we want to target a specific Post or Page, we need to take advantage of Conditional Tags that are available in WordPress. For example, if we want to target a specific post with ID 100, we can add the following conditional logic in our code:
function ple_hook_javascript() {
if ( is_single ('100') ) {
?>
<script>
// Your JavaScript code goes here...
console.log("This will only load on Post with ID 100");
</script>
<?php
}
}
add_action( 'wp_head', 'ple_hook_javascript' );
In the code above, is_single checks whether the query is for a specific single post. You can find the Post ID in the URL Address bar, as you can clearly see in the next screenshot.
You can use various Conditional Tags to target specific Posts, Pages or Custom Post Types. For example, you can use the following code to inject the script only when the pages with ID 36 or with the title “Contact” are loaded:
function ple_hook_javascript() {
if ( is_page( array( 36, 'Contact' ) ) ) {
?>
<script>
console.log("This will only load on Page with ID 36, or on Page with title 'Contact'.");
</script>
<?php
}
}
add_action( 'wp_head', 'ple_hook_javascript' );
If we want to inject our script tag right before the closing </body> tag, we can use the wp_footer action hook. The same Conditional Tags logic applies here also.
function ple_hook_javascript() {
?>
<script>
// Your JavaScript code goes here...
</script>
<?php
}
add_action( 'wp_footer', 'ple_hook_javascript' );
This method is quite handy, because it allows us to embed our JavaScript globally (across all pages) or on specific posts or pages, using the Conditional Tags. It also allows us to inject inline code inside the <script></script> tags or load an external script by using the <script> src attribute and it basically does what any add header & footer scripts plugin does.
When it comes to loading JS libraries and work with library dependencies though, we must take a closer look at the next method which uses enqueueing to deal with dependency management.
Registering and Enqueueing Scripts
Using the wp_enqueue_script
and admin_enqueue_script Hooks
When it comes to dependency management (scripts that depend on other scripts in order to function properly), WordPress provides a couple of handy functions and hooks that we can use to apply some fine control over our script loading.
In contrast to the wp_head and wp_footer Hooks, which directly inject custom markup and scripts in the <head></head> and </body> sections of the page, the family of wp_register_script(), wp_enqueue_script() and admin_enqueue_script() functions ensure that all scripts are loaded in an orderly fashion along with their dependencies.
Enqueueing Scripts
Let’s enqeue a custom script that requires the jQuery library in order to run. We are going to create a folder named js/ in our child theme directory, place a script named custom.js in it and then load the script in all of our pages. We are going to edit our child theme’s functions.php file and add the following code:
function myprefix_enqueue_scripts() {
wp_enqueue_script(
'my-script',
get_stylesheet_directory_uri() . '/js/custom.js',
array('jquery'),
'1.0.0',
true );
}
add_action( 'wp_enqueue_scripts', 'myprefix_enqueue_scripts' );
The snippet above, will ensure that the jQuery library is loaded first and then load our custom.js right before the closing </body> section using the wp_enqueue_scripts action hook. Let’s break the five wp_enqueue_script() arguments one by one:
‘my-script’ This is the script’s unique handle name.
get_stylesheet_directory_uri() . ‘/js/custom.js’ This is the location of our JS script, dynamically retrieved from the current theme directory using the get_stylesheet_directory_uri() function, which returns the child theme directory address or the parent theme’s if you don’t have a child theme activated (we strongly suggest that you do).
array(‘jquery’) This is how we instruct WP to load the required JS dependencies (JS libraries, scripts) along with our script. We can add as many script handle names as we like. For a list of handle names for the JS libraries bundled with WP, check this link.
‘1.0.0’ An optional version for our custom script.
true This is an optional parameter that if set to true, places the script in the footer or if left to the default value of false, places the script inside the <head> tag.
You can also pass an external URL to the wp_enqueue_script() function and load a script or library from another server, for example:
function myprefix_enqueue_scripts() {
wp_enqueue_script(
'my-script',
'https://cdnjs.com/library.js'
);
}
add_action( 'wp_enqueue_scripts', 'myprefix_enqueue_scripts' );
Keep in mind, that the wp_enqueue_scripts action hook, loads the enqueued scripts on the front end pages. If you want to load a script on the backend WP admin area, you must use the admin_enqueue_scripts and if you want to enqueue your scripts for the login screen, you must use the login_enqueue_scripts action hook. Here is an example of loading a script on our backend area:
function myprefix_enqueue_scripts() {
wp_enqueue_script(
'my-admin-script',
get_stylesheet_directory_uri() . '/js/admin.js',
array('jquery'),
'1.0.0',
true );
}
add_action( 'admin_enqueue_scripts', 'myprefix_enqueue_scripts' );
Registering Scripts
Although, using the *_enqueue_scripts family of functions on their own is considered a valid and safe way to load scripts on your pages, WordPress provides us with a complementary function called wp_register_script, that enables us to register scripts before enqueueing and actually loading them.
By registering our scripts beforehand, we get the following advantages:
– Use our registered scripts as dependencies for other scripts: WordPress will automatically include our registered scripts before loading the enqueued script(s) that include the registered script’s handle in its list of dependencies.
– Avoid conflicts and loading the same script multiple times
– Easily enqueue the same script(s) in more than one place, just by using the registered script’s handle name instead of repeating the same code.
– Register your script(s) and load them only when you need them, e.g. conditionally on specific pages.
– Enqueue your script(s) once and load them both on the front end and backend just by using the handle name and without any additional parameters.
Let’s see an example:
add_action('init', 'myprefix_register_scripts');
function myprefix_register_scripts() {
wp_register_script( 'script1', get_stylesheet_directory_uri() . '/script1.js' );
wp_register_script( 'script2', get_stylesheet_directory_uri() . '/script2.js' );
}
After registering your script(s), you can add it on your pages by calling the wp_enqueue_script() function with the script handle as its first argument. You can also conditionally enqueue the same script(s) in the backend using the admin_enqueues_script() function:
add_action( 'wp_enqueue_scripts', 'myprefix_enqueue_scripts' );
function myprefix_enqueue_scripts() {
if ( is_front_page() ) {
wp_enqueue_style( 'script1' );
} elseif ( is_page_template( 'booking.php' ) ) {
wp_enqueue_style( 'script1' );
wp_enqueue_style( 'script2' );
}
}
add_action( 'admin_enqueue_scripts', 'myprefix_admin_scripts' );
function myprefix_admin_scripts() {
wp_enqueue_style( 'script2' );
}
Adding Inline Scripts
Yet another script helper function in WordPress is the wp_add_inline_script() which gives us the capability to add inline JavaScript code right before or after a registered or enqueued script.
Here’s a practical example to add Typekit’s JavaScript to your site:
function mytheme_enqueue_typekit() {
wp_enqueue_script( 'mytheme-typekit', 'https://use.typekit.net/.js', array(), '1.0' );
// We use the handle name 'mytheme-typekit' of the typekit enqueued script
// as our code's dependency:
wp_add_inline_script( 'mytheme-typekit', 'try { Typekit.load({ async: true }); } catch(e){ }' );
}
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_typekit' );
This will result in the following markup:
<script type='text/javascript' src='https://use.typekit.net/<typekit-id>.js?ver=1.0'></script>
<script type='text/javascript'>
try { Typekit.load({ async: true }); } catch(e){ }
</script>
Adding Localized Data
Passing data from PHP to JS
But, what about when you want to pass some data from your PHP code to your JavaScript?
WordPress provides a handy function called wp_localize_script that does exactly that: makes your PHP data accessible to your JS scripts.
Let’s go through a simple example:
In your child theme’s functions.php:
Create a file named custom.js and place it in a folder named js/ inside your child theme’s directory, and add the following code:
In our PHP code, we are enqueuing a JavaScript file and then use the wp_localize_script() to pass our data (The 3rd argument, the associative array) to a JavaScript object named php_data that will be available in our JavaScript code. As you can see, we are passing the enqueued or registered script’s handle name as the first argument on our wp_localize_script function call.
The JS object – in our case named php_data – will be available globally, so make sure that you carefully pick a prefixed custom name to avoid variable conflicts in your JavaScript code.
Add JS using WordPress Plugins
If you think that the available native methods discussed above are quite complicated or limiting in some way, or you feel more comfortable working with plugins, there’s no need to worry. Numerous quality and easy-to-use plugins are available for you from the WordPress plugin repository. Here is a list of the most popular plugins:
The “Insert Header and Footer” Plugin
This is probably the most widely used plugin for embedding JavaScript code on a WordPress site. You can download the plugin from this link.
Developed by WP Beginner and ideal for site-wide JS scripts, this plugin will add the JavaScript code to all the pages of your website, either in the wp head or wp footer areas.
To install, go to Plugins > Add New > and search for “Insert Headers and Footers“.
Upon activation, you need to visit Settings » Insert Headers and Footers page. You will see two boxes, one for the header and the other for the footer section. You can paste the JavaScript or jQuery code to one of these boxes and then click on the save button. Insert Headers and Footers plugin will now automatically load the code you added on every page of your website.
You can use this plugin to embed third-party code that requires to be executed on all pages, for example a Google Analytics script that keeps track of your website’s pages. You can also load an external script or a custom script that you have uploaded on your website.
In case you want to execute a JavaScript code on specific Post(s) or Page(s) you will need to add some conditional logic to your code. For example you can use the unique .postid-# class applied automatically by WordPress on each Post and Page. We have created a video walkthrough to help you accomplish that and a sample snippet that you can use for the conditional logic.
The “Simple Custom CSS and JS” Plugin
With over 100,000 downloads, this plugin works much like the Insert Headers and Footers plugin and allows you to insert custom JavaScript and CSS on your website. You can download the plugin or read the reviews about it here. Below is a quick video walkthrough for adding a JS script using the plugin.
The “Scripts n Styles” Plugin
This is another plugin that enables you to embed custom scripts in your site’s <head> or </body> section, either on a specific post/page or on all pages. The setup and configuration of this plugin is extremely easy, and you can see a video walkthrough of how to add JavaScript on specific pages or sitewide below. You can download the plugin here.
The “Shortcoder” Plugin
Last, but not least, a plugin that enables you to create as many shortcodes as you like and embed them on any Post or Page. In addition to executing JavaScript on your pages through these shortcodes, you can dynamically pass various Post parameters to your JS code (e.g. Post ID, Post title, etc.) as well as custom values through custom shortcode parameters and thus create variations of your code.
Adding JS using the
WPBakery Page Builder
This post wouldn’t have been complete, without mentioning how one of the most popular Page Builders for WordPress allows us to embed custom JavaScript code on our Posts, Pages and Custom Post Types. The Raw JS element of WPBakery Page Builder, enables us to insert <script> tags that include custom JS code as well as load external libraries through the src attribute. You can watch a video walkthrough below.
Overview
SITE-WIDE* | SPECIFIC POST/PAGE | HEAD | FOOTER | EXTERNAL JS | INLINE JS | CUSTOM POST TYPE | PLUGIN | |
---|---|---|---|---|---|---|---|---|
Custom HTML ( Gutenberg Block ) |
||||||||
Classic Editor ( Text Mode ) |
||||||||
Action Hooks ( wp_head, wp_footer ) |
||||||||
wp_enqueue_script / wp_register_script | ||||||||
Insert Headers & Footers | ||||||||
Simple Custom CSS & JS | ||||||||
Scripts n Styles | ||||||||
Shortcodes | ||||||||
WPBakery Page Builder |
Summary
When it comes to adding JavaScript to WordPress, there are quite a few options. You must carefully review each of the aforementioned methods, and choose the one that best suits your requirements without overloading your website with unnecessary requests and script execution. When selecting the most appropriate method, take the following tips into consideration:
– If you are planning to use your script on a specific page or post, choose the method that enables you to do exactly that. You don’t need the execution of a script or an extra HTTP request on pages that don’t use or need the code.
– Choose a method that executes or loads a script on all pages, when the code requires it, for example when you want to add tracking on your website (e.g. with Google Analytics).
– Get into the habit of using the try { } catch { } JavaScript blocks when writing and embedding your own custom code, in order to avoid conflicts with other scripts or get into the uncomfortable situation of having your code errors break all subsequent JavaScript on your website’s pages.
– When your code manipulates HTML elements in your pages, ensure that the content has been loaded beforehand by enclosing the code in a jQuery callback or by using the DOMContentLoaded event in the case of vanilla JavaScript, as shown in the code below:
// jQuery code:
jQuery( function( $ ){
// Safely use the $ alias here
// Code here will be executed on the document.ready event
});
// Plain ( vanilla )JavaScript code:
document.addEventListener( "DOMContentLoaded", function(){
// Code here will be executed when the document has been loaded
});
Troubleshooting
Problem: My code is not working. It produces an error: $ is not a function
Solution: Use jQuery instead of $. Moreover, you can safely wrap your jQuery code in a callback and use the $ alias inside, like this:
jQuery( function( $ ){
// Safely use the $ alias here
// Code here will be executed on the document.ready event
});
Thank you!
If you enjoyed reading this post and found it helpful, please spread the word and leave your comments below. Also, don’t forget to visit our WordPress Themes on Themeforest!
Life saving article! Thank you so much.
Hi Iftekhar! We appreciate your kind words. Your feedback is valuable to us!
This is an excellent, comprehensive article. Wish I had it in hand a year ago when I was trying to figure this stuff out!
Thank you.
Thank you, Dennis. We were hoping it would be useful. Considering the usefulness of Javascript, knowing where and how to apply a script is of great value for any website.
This is a fantastic synopsis! Thanks so much for posting this info. I was looking for a PHP solution to our problem, and this provided some much appreciated information. Thank you Plethora Themes! Do you work with any small developers on special projects? If so, I would love to communicate with Kostas about our project. Thanks again for posting!
Thank you very much for the feedback Stuart. One of our members will be contacting you.
Thank you so much for the response! I am working on a project that is super cool and is sort of inline with what you guys do with the Hotel Xenia Theme but for a different Industry. And, we are open to building a theme with an extensive backend that is currently stable for custom sites, and would love to migrate to WP. Hence the PHP scripting help. Lot’s of possibilities and some funding.