Qi Theme

Get a completely FREE WordPress theme. Qi Theme has 100 modern demo websites

Get Free Theme
Sign up for our newsletter and be the first to get all the latest Qode news and updates.
BACK TO TOP

How to Add Custom JavaScript to Your WordPress Website

How to Add Custom JavaScript to Your WordPress Website

JavaScript code can be added to your WordPress website for various purposes, usually to improve a feature or add functionality. Regardless of the reason you’re adding JavaScript (JS) to your website, it is important to properly create, place and keep up this code. Incorrect code placement can hurt the site’s performance or even break it.

In this article, we will show you several ways to add the JavaScript code. Let’s begin!

How To Add JavaScript To WordPress – Theme Options

Some WordPress themes incorporate a field for including JS code. To see if that’s the case with your website theme, review its available options. If the option exists, insert the JS code in the designated place, if it exists.

For example, all WordPress themes created by Qode Interactive allow you to insert JS code in the theme settings. You can access them by navigating to Theme_name Options > General. Scroll down to the section called Custom Code and insert your JS code in the Custom JS field.

Theme Options

Using Plugins

One of the many benefits of WordPress is a wide array of available plugins for just about any functionality you can think of. Therefore, adding JS code to your WordPress site can be as simple as finding the plugin that best suits your needs.

JavaScript plugins can be free, premium, or even come bundled with the themes. In this article, we will cover several examples of these plugins, but if they don’t seem like the right fit, you are free to explore beyond this list.

Plugin Shortcodes

Some plugins, like WPBakery Page Builder, have shortcodes for adding JS to individual pages and posts. In WPBakery, this shortcode is called Raw JS.

If you don’t have this plugin, first you have to install it and activate it. Then, go to the backend of a page or a post, and click on “Add Element”.

Add Element

Search for “Raw JS” and click to add the shortcode.

Raw JS shortcode

The only thing left to do is add the code within the shortcode. By creating the shortcode, you also create a dummy JS code. Add your code between the opening <script> tag and closing </script> tag.

If you delete the dummy JS code, you have to make sure that the code you insert has both the opening <script> and the closing </script> tag.

Raw JS Shortcode
Raw JS Shortcode

If you are using this method to add JavaScript to your website, it is strongly recommended that you add JS code that is smaller in size. Otherwise, the page loading speed could decrease. If you want to include larger JS code, consider using a different method.

How To Add JavaScript To WordPress – Plugin Options

Most plugins offer options for including JS code. Depending on the plugin, this code can be applied site-wide, or be page-specific. In this section, we will describe the Insert Headers and Footers plugin, as it is a widely recommended solution.

This plugin is used to implement site-wide JS code, although the code can be adjusted for specific pages or posts only. For the purposes of this guide, we will focus on the site-wide code, since the intricacies of additional code adjustments warrant a separate article.

One example of popular site-wide code is the Google Analytics code. To install the plugin, navigate to Plugins, click on “Add New” and type a keyword (“Headers”, for example) in the search bar. Click on the result, install it, and don’t forget to activate it – the installed plugin won’t work unless it is activated.

Headers and Footers Plugin

To use the plugin, go to Settings, click on Headers and Footers, and insert your code either in the Scripts in the Header or Scripts in the Footer section.

Headers and Footers Options
Headers and Footers Options

Here’s another tip: inside the Scripts in the Header field, include the code that is a part of the <head> section and applied site-wide. This includes Google Analytics code, stylesheets or code concerning <meta> tags, for example. The rest should be placed in the “Scripts in Footer” section, especially if the JS code is adjusted to be page-specific.

However, if the code isn’t working when you add it to the first section, try to remove it and add it to the second section.

Another way to add JS code is to add it directly to the appropriate section.

Adding Scripts

If you have larger JS scripts, you can create a stylesheet (a file with a .js extension), upload it to the dedicated JS folder inside your theme and include its path. The path will most likely be one of the following two:

wp-content/themes/theme_name/js

Or

wp-content/themes/theme_name/assets/js

Add the line of code with the path to the uploaded file. Depending on the path, the src attribute will vary. Here are two possible examples:

<script src="your_website_url/wp-content/themes/theme_name>/js/filename.js"></script>

Or

<script src="your_website_url/wp-content/themes/theme_name>/assets/js/filename.js"></script>

When you use this line, the entire code from the uploaded file will be loaded when the script is run.

Adding Scripts

Make sure the code you add has both the opening <script> and the closing </script> tag.

Always check your site thoroughly after adding the JS code. Although JavaScript code can improve the functionality of certain pages, it can harm others by overlooking the outlying cases.

If you don’t think this plugin is the right fit for you, we encourage you to explore the WordPress.org plugins page or tell us about your experiences with JS inclusion plugins in the comments.

Now let’s move onto more coding-focused solutions. These will require a somewhat deeper understanding of WordPress, so they are a good choice for developers. If you want to give them a try despite not being WordPress savvy, try doing some additional research to prepare.

Qode WordPress Themes: Top Picks
Bridge WordPress Theme Banner
Bridge

Creative Multi-Purpose WordPress Theme

Stockholm WordPress Theme
Stockholm

A Genuinely Multi-Concept Theme

Startit WordPress Theme
Startit

Fresh Startup Business Theme

Biagiott banneri
Biagiotti

Beauty and Cosmetics Shop

More Advanced Methods

Before we show you coding solutions for JavaScript, we will address some bad coding practices and habits you should avoid.

One bad practice you should avoid at all costs is directly adding JS code inside your theme’s header.php and footer.php files. This also extends to the file path inclusion of a certain uploaded JS file, both inside header.php, and footer.php.

Why is this such a bad idea? Whenever your theme is updated, your code will be lost during the all-encompassing override of the theme files. There are ways to avoid this by copying header.php and footer.php files inside a child theme.

However, it can still lead to conflicts with the plugin-loaded JS scripts, which is precisely why this method is not recommended. Now let’s look into the right ways to add JavaScript to your WordPress website.

Using wp_head and wp_footer Hooks

A method that is less encouraged, but still better than directly including the code, is adding the code using the wp_head and wp_footer hooks. Hooks are a way of changing the default behavior of themes, plugins, and WordPress, without changing its template files.

You can add the code both inside the theme and plugins, created specifically for your site. We recommend you use the functions.php of your child theme, so you can preserve the changes after theme updates. Another suggestion – add smaller JS code scripts.

Why is this method not encouraged? While it may seem effective at first, adding too much code can easily become hard to keep up with. Furthermore, it can cause certain scripts to load multiple times, decreasing the speed of your website. So, this method will serve you well only with careful and limited use.

If you are sure you want to add JavaScript this way, simply insert one of these 2 blocks of code inside your functions.php (or functions.php of your child theme), depending on whether you want to hook onto wp_head or wp_footer.

function my_javascript_code() {
?>
<script>
// your javascript code goes here
</script>
<?php
}
add_action('wp_head', 'my_javascript_code');
Javascript Hooks Code
function my_footer_javascript_code() {
?>
<script>
// your javascript code goes here
</script>
<?php
}
add_action('wp_footer', 'my_footer_javascript_code');
Javascript Hooks Code WP Footer

It is also possible to apply the JS code selectively, using WordPress conditional tags.

We will include two possible examples:

  • page-specific code, for a page called “About Us” and
function about_us_javascript_code() {
if ( is_page( 'About Us' ) ) { ?>
<script>
// your javascript code goes here
</script>
<?php }
}
add_action( 'wp_head', 'about_us_javascript_code' );
Wp Head Code
  • post-specific code, for the post with the ID of 30.
function my_post_javascript_code() {
if ( is_single( '30' ) ) { ?>
<script>
// your javascript code goes here
</script>
<?php }
}
add_action( 'wp_head', 'my_post_javascript_code' );
Wp Head Code

The ID’s of the posts are visible when you’re editing. The ID number is located within the URL after the “post=” part.

Post ID

Needless to say, it is important to take care of the proper code syntax in the opening and closing tags, both for PHP and JavaScript.

Similar codes can be created and “hooked onto” wp_footer hook. Wp_head hook is located before the closing of the </head> tag, while the wp_footer is located before the closing of the </body> tag. We recommend that you hook the code onto the wp_footer hook to avoid decreased loading speeds of your website, especially if the code is larger in length.

Using wp_enqueue_script

The most effective method of adding JavaScript code to your WordPress site is creating a separate .js file, inserting it in the proper place and then using the wp_enqueue_script function.
More precisely, this means you’ll add wp_enqueue_script to another function that is hooked to one of the two WordPress script loading hooks – wp_enqueue_scripts.

This method is preferred by developers of any well-coded theme. It bypasses the downsides of the previously described methods, such as plugin conflicts and loading the same script multiple times. Also, WordPress offers a list of registered, widely used scripts, in order to improve this process even further.

Similarly to the method we described in the previous section, this method requires the following:

  • Creating a file with the .js extension
  • Placing the file in the designated place within the theme or plugin
  • Proper use of the wp_enqueue_script function

We will clarify things by explaining some of the possible uses of this function.

As noted in the description, the wp_enqueue_script function has 5 parameters. Out of these five parameters, only the first one is required. That is the unique handle name.

  • The code you can see below enqueues a script with the handle “dev-script”. The path to the file is wp-content/themes/theme_name/js/devscript.js.
Devscript Image

The remaining parameters are set to default values. This means the function has no dependent scripts, its version is the same as the currently installed WordPress version, and it is enqueued before the closing of the </head> tag.

The code should be placed inside the functions.php file of your (parent) theme.

Devscript Functions
function my_dev_script() {
wp_enqueue_script( 'dev-script', get_template_directory_uri() . '/js/devscript.js');
}
add_action('wp_enqueue_scripts', 'my_dev_script');
  • Script enqueued bellow has the handle “appear”, while the path to the file is wp-content/themes/child_theme_name/assets/js/ jquery.appear.js. The function is dependent on the script with the handle “jquery”. Its version is the same as the currently installed WordPress version and it is enqueued before the closing tag.

The code should be placed inside the functions.php file of your child theme.

function js_appear_script{
wp_enqueue_script( 'appear', get_stylesheet_directory_uri() . '/assets /js/ jquery.appear.js', array( 'jquery' ), false, true );
}
add_action('wp_enqueue_scripts','js_appear_script');
  • Script handle is “very-compatible”, path to the file is wp-content/plugins/plugin_name/’assets/js/compatible.js. The function has no dependent scripts, its version is 3.5 and it is enqueued before the closing </body> tag.

The code should be placed in one of the files of your plugin. The same plugin where you previously inserted the .js file.

function my_compatible_script() {
wp_enqueue_script('very-compatible', plugins_url('assets/js/compatible.js', __FILE__), array(), '3.5', true);
}
add_action('wp_enqueue_scripts','my_compatible_script');
  • The code below first registers the script with wp_register_script function and then enqueues.

The wp_register_script function has the same parameters as the wp_enqueue_script, so it doesn’t require additional explanation. Given all the parameters, the wp_enqueue_script function already registers the JS script, which is why using the wp_register_script is not necessary.

However, the main benefit of using both functions is that the same script can be de-registered using wp_deregister_script, and then re-registered with the same handle and different remaining parameters.

function register_and_add_script() {
wp_register_script('my-js-script', get_template_directory_uri() . '/assets/js/my_js_script.js', array('jquery'),'3.4.1', true);
wp_enqueue_script('my-js-script');
}
add_action( 'wp_enqueue_scripts', 'register_and_add_script' );

Using wp_add_inline_script

This method of adding JS code is best used in conjunction with the previously described method. While using wp_enqueue_script is better suited for adding large scripts, the wp_add_inline_script is the best choice for smaller JS code inclusions.

Wp_add_inline_script function adds the JS code to an already registered script, either at the beginning or at the end. Therefore, the steps are as follows:

  • Using wp_enqueue_script
  • Placing the file in the designated folder
  • Creating the .js file
  • Using wp_add_inline_script

Both of the functions should be used within a function that “hooks” on to wp_enqueue_scripts.

Here’s one example of this type of function. It should be placed inside the functions.php of the (parent) theme.

function inline_custom_js() {
wp_enqueue_script( 'theme-js-script', get_template_directory_uri() . '/js/modules.js', array( 'jquery' ), false, true );
$custom_js = 'insert-your-inline-javascript-here';
if ( ! empty( $custom_js ) ) {
wp_add_inline_script( 'theme-js-script', $custom_js );
}
}
add_action( 'wp_enqueue_scripts', 'inline_custom_js' );

Final Thoughts

In this guide on JavaScript code inclusion in WordPress, we tried to cover all the levels of difficulty and efficiency. We’ve also given you an opportunity to weigh the pros and cons of each method.

Depending on your needs and knowledge, you can find the method that suits you the best. You can also use this tutorial to learn something new and get to know your WordPress website a little bit better.

Post your comment

Comments0