How to Add Javascript (files or scripts) Without Breaking Your WordPress Site (functions.php, template or plugin)

Add Javascript to WordPress

There are typically many reasons why you want to add Javascript to WordPress, either a small tweak to a feature or maybe you're looking to add a 3rd party script. Regardless of the reason why you want to do it, you want to make sure you don't get it wrong - because you might ruin your website.

There is a good way of adding Javascript to WordPress. And then there are the bad ways, which could either break your website or else create a negative impact on performance.

In this article, we will suggest a number of different ways for adding Javascript code to websites and which ones should be used in the different circumstances you may encounter.

Contents[Show]

 

WordPress is so extensible that it allows you to easily add new features and functionalities to your website without actually having to redesign or replace your entire theme. Rather than recreating the WordPress theme from scratch, you can add the functionality by simply adding plugins.

And if the functionality you would like to add is rather small, and there's no need to create or install a plugin, you can use the functions.php file or various other ways to add Javascript to WordPress without having to create a separate plugin.

(Special note: Are you looking for a list of tweaks/tricks you can easily make on your WordPress site without using a plugin? You may refer our guide here:101 WordPress tricks every serious blogger must know.)

The best thing about the functions file is that it acts like a plugin, that can be used to add features and extend the functionality of both the theme as well as WordPress itself.

Though you can easily add Javascript code directly to your header.php file, there is a problem with this method.

It can actually cause conflicts with other plugins when they load their own JS scripts.

In this article by CollectiveRay, we take a look at the right way to add javascript to WordPress themes. As WordPress developers, this is one of the things which we will have to do very often.

If you're not confident of tweaking the code yourself, you might want to look at this article to learn how to recruit the best WordPress developer for your business: https://www.collectiveray.com/wordpress-developers-for-hire, or find check out the following cheap development options. 

If you're not sure about whether this is right for you and what to get this done quickly, check out a few Fiverr gigs who can get this done for you quickly

fiverr logo

Click here to find cheap experts on WordPress fixes

 

How to Add JavaScript to WordPress

There are multiple ways to add custom Javascript code to your WordPress site, each with their own uses:

  1. Add the script to a specific or single page of your choice, or multiple pages using functions.php
  2. Add a script into select pages using plugins such as Headers and Footers
  3. Add a Javascript file to your theme header

1. Using functions.php

Single Page or Post

This code tweak will use the functions file found in your template folder to add a .JS file of your own choice to a single page of your own choice only.

This uses the IS_PAGE function which you can find here: https://developer.wordpress.org/themes/basics/conditional-tags/. You can actually use various other options if you want to add the script only in specific conditions such as:

  • is_single(),
  • is_front_page(),
  • is_home,
  • is_admin etc. 

If you prefer to watch a video on YouTube on how to do this, this short video is quite a good one, on how to add Javascript to a single page:

Fw6VDOZYqrM

We have detailed instructions on the page, so once you've seen the video, you can use this article as your reference.

If you need to add the file to all pages, keep on scrolling to find other alternatives to this method below.

  • First, you'll need to identify the ID of the page which you want to add the script to. You do this by going to the page, you want to add the file to, click Edit and then pickup up the ID of the page from the URL as you can see below. The ID is the number found in the URL of the browser bar.
  • wordpress page id

  • Now that you have the ID of the page, you will need to upload the .js file to a location. We would recommend that you upload the .js file to your template folder, maybe in the child directory.
  • Once you've uploaded that, you need to take note exactly of the directory and the name of the .JS file, which we use instead of PATH_TO_JS_FILE below. As an example, your file might be in: https://www.yourwebsite.com/wp-content/themes/twentynineteen/js/myjsfile.js
  • Take full note of that full URL and replace the PATH_T_JS_FILE below. You will also need to replace ID which you have found from above.
  • Add the full code below to the end of the functions file of your template.

function collectiveray_load_js_script() {
  if( is_page(ID) ) {
    wp_enqueue_script('js-file', 'PATH_TO_JS_FILE', array('jquery'), '', false);
    //or use the version below if you know exactly where the file is
    //wp_enqueue_script( 'js-file', get_template_directory_uri() . '/js/myscript.js');
  }
}

add_action('wp_enqueue_scripts', 'collectiveray_load_js_script');

If you know exactly where you have placed the JS file, you can use a slight variation of the wp_enqueue_script: 

wp_enqueue_script( 'js-file', get_template_directory_uri() . '/js/myscript.js');

In this case, the /js/mysript.js file is the location of the file you want to add.

Once you reload the page, you'll find that the file has been added. You can confirm this by clicking on View Source of the page.

If instead of adding the Javascript file to a page, you want to add it to a single page, we can use a slight tweak of this function, to make it apply to a single post. You can use any variation of the following:

  • is_single( ’17’ ) - uses the post ID
  • is_single( ‘My Post Title’ ) - uses the title of the post to check whether this is the post to add the file to
  • is_single( ‘my-post-title’ ) - checks against the slug of the post
  • is_single( array( 17, ‘my-post-title’, 'My Post Title’ ) ) - this checks if any of the conditions post ID is "17", slug is "my-post-title", or title is "My Post Title"
  • is_single() - other variations of the is_single function using an array of values to check against

The code, in this case, would be the following or a slight variation depending on the parameters of the is_single function. 

function collectiveray_load_js_script() {
  if( is_single('17') ) {
    wp_enqueue_script('js-file', 'PATH_TO_JS_FILE', array('jquery'), '', false);
    //or use the version below if you know exactly where the file is
    //wp_enqueue_script( 'js-file', get_template_directory_uri() . '/js/myscript.js');
  } 
}

add_action('wp_enqueue_scripts', 'collectiveray_load_js_script');

If you have the post title, you can use this, instead of the parameter "17". Once again the wp_enqueue_script can also be tweaked to:

wp_enqueue_script( 'js-file', get_template_directory_uri() . '/js/myscript.js');

Add Javascript to all pages 

As we have seen, the easiest and cleanest method to add a javascript file to your WordPress theme is by using functions.php file with wp_enqueue_script. In this case, instead of creating a condition to add the content to specific pages, we're going to add a generic function.

Here’s how to do it:

Open your functions.php file and copy the below code snippet to it. Make sure you replace the template URL with yours before saving.

function collectiveray_theme_scripts_function() {
  wp_enqueue_script( 'js-file', get_template_directory_uri() . '/js/myscript.js');
}
add_action('wp_enqueue_scripts','collectiveray_theme_scripts_function');

If you’re using a child theme, you’ll need to use get_stylesheet_directory_uri() instead of get_template_directory_uri() 

2. Using plugins

If you would like to simply use a plugin for embedding a javascript reference to the WordPress theme’s header or footer file, ‘Insert Headers and Footers’ plugin is an easy option.

As the name says it allows you to add scripts to the header and footer files by hooking into wp_head and wp_footer functions of WordPress. 

This plugin is a good option because it allows you to add any script without running any risk of breaking stuff. Moreover, you don't have to change or tweak any code yourself (if you're not comfortable doing that), like we had to do in the previous example.

Changing code directly is typically a better option for web designers. The method using this plugin is easier.

Instead of modifying the theme's files directly with the custom Javascript code, the plugin allows you to insert the code, which will then be added to the header or the footer of your site, depending on the options you've chosen. 

This plugin supports two options:

  1. Adding the path to a specific Javascript file which you upload
  2. Adding the script directly (e.g. for Analytics or other 3rd party scripts)

Let's get started: 

You can download Insert Headers and Footers here.

Install the plugin:

  • Log in to your site's backend or admin.
  • Go to Plugins > Add new
  • Search for "Headers and Footers" plugin and click on Install Now.
  • Once it has installed, click on Activate
Headers and footers
Depending on your scenario, you now need to follow option 1 or 2. For example, to add Google Analytics, you need to follow option 2.

Option 1: Upload a custom Javascript file

  • First, you need to prepare the file for inclusion
  • Save your JavaScript code or file into a new test file with the .js extension.
  • Upload it into your site to the following folder: wp-content/themes/<theme-you-are-using>/js/
  • Go to Settings > Insert Headers and Footers.

We now have a couple of choices to load our file:

  1. Scripts in header (load inside <head> tag)
  2. Scripts in footer (load before closing </body> tag)

Use the location that matches best your specific needs using the following as an example. Note that <theme-you-are-using> needs to be changed to the name of the directory of the theme you are using, e.g. twentytwenty

<script src="https://www.website.com/wp-content/themes/<theme-you-are-using>/js/file.js"></script>
 
Insert script in head
  • Click on the "Save" button to finish and save.

Option 2: Load custom script without a file

The 2nd option you can use with this plugin, is the option to the add the code directly into WordPress without the need of using a specific file.

This can be used when you are using a 3rd party service, such as Google Analytics, Drip, or another tool which needs some script added to your site. Just take the script and drop it into the Scripts in Header window:

add script / code directly
 
Once again, click "Save" to finish.

 

Reload the front-end, and check your website's source to make sure that the code is now showing. It's also a good idea to browse a few pages to confirm that everything is still working well.

 

Even though this seems fairly simple, it might be out of your comfort zone, so if you want to get this done quickly, check out some developers on Fiverr who can get this done for you.

fiverr logo

Click here to find cheap experts on WordPress fixes

 

 

If you found this tip useful, you might want to check out more of our WordPress tips at the relevant menu at the top of the page.

3. Add JavaScript to Your Theme Header

In certain cases, you might want that the JavaScript file is used in all your site, but you don't want to use a plugin to do this.

For example, if you want to add a 3rd party script in all your pages, (e.g. the instantpage.js script to make your website faster) you can insert the script, or add the referenced script file itself, in the head of your header.php template file. 

THIS IS NOT IDEAL. If you update your theme, you might lose these changes. If you still would like to do this directly, it is highly recommended that you create a child theme.

For this scenario, where you want this script to be added everywhere, you can add the file directly to the template as per the instructions below:

This call to the file (or script) should be added between the meta tags and the style sheet link. This is exactly the same as if you were adding Javascript code in any HTML page. 

To "add" the Javascript file into your site, in the head, you use the following code:

<script type="text/javascript" src="/scripts/myscript.js"></script>

Make sure that you have defined the type correctly, otherwise your site will not be valid. Also make sure that the directory /scripts exists in the theme and you have added the myscript.js to it.

You can then add any reference to functions used within the file you just added to the HTML where you need to use it. 

For example, this is an example of using the function you just added.

<h3 class="heading3">
<a href="<?php the_permalink() ?>" >
Heading goes here</a></h3>
<div>
<script type="text/javascript">
<!--
myscript();
//--></script>
</div>

 

Download the list of 101 WordPress tricks every blogger should know

101 WordPress tricks

Click here to Download Now
 

Frequently Asked Questions

How do I add a Javascript file to WordPress?

The easiest way to add a Javascript file to WordPress is using the Insert Headers and Footers plugin. 

  • Log in to your site's and install Headers and Footers plugin.
  • Once it has installed, click on Activate
  • Save your JavaScript code or file into a new file with the .js extension.
  • Upload it into your site to the following folder: wp-content/themes/<theme-you-are-using>/js/
  • Go to Settings > Insert Headers and Footers.
  • Add the following to the Scripts in Header:  <script src="https://www.website.com/wp-content/themes/<theme-you-are-using>/js/file.js"></script>

 

Can I use Javascript in WordPress?

Yes, there are many ways of using Javascript in WordPress. If you want to add a simple script, you can use the Insert Headers and Footers plugin to add the script to header, then call the script from whatever part of the theme, post or plugin you need to use it from.

How do I add my own code to WordPress?

The best way to add your own code to WordPress is through the functions.php file. It is recommended that you create a child theme and then add your own modifications to the child theme such that you don't break the upgradability of your theme.

How do I edit Javascript in WordPress?

The best way to edit Javascript in WordPress is by creating a child theme, then add your edits of Javascript or customization of other functions in the child theme. This allows you to edit Javascript as necessary without breaking the rest of your theme or the upgradeability of the theme.

Conclusion

The above three methods are the cleanest way to add Javascript to WordPress. In general, tweaking the code directly should be done by advanced users who have significant code experience and can be sure they know how to revert any changes they've made. Otherwise, it is best to stick to plugins.  If you're not comfortable tweaking the code yourself, it would be great to get in touch with our partners on Fiverr who can get it done for your today

fiverr logo

Click here to find cheap experts on WordPress fixes

 

About the Author
David Attard
Author: David AttardWebsite:https://www.linkedin.com/in/dattard/
David has been working in or around the online / digital industry for the last 18 years. He has vast experience in the software and web design industries using WordPress, Joomla and niches surrounding them. As a digital consultant, his focus is on helping businesses get a competitive advantage using a combination of their website and digital platforms available today.

One more thing... Did you know that people who share useful stuff like this post look AWESOME too? ;-)
Please leave a useful comment with your thoughts, then share this on your Facebook group(s) who would find this useful and let's reap the benefits together. Thank you for sharing and being nice!

Disclosure: This page may contain links to external sites for products which we love and wholeheartedly recommend. If you buy products we suggest, we may earn a referral fee. Such fees do not influence our recommendations and we do not accept payments for positive reviews.

Author(s) Featured On:  Inc Magazine Logo   Sitepoint logo   CSS Tricks logo    webdesignerdepot logo   WPMU DEV logo   and many more ...