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, is the how which many people get wrong.

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 an 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 that 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 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, which 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 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 other cheap development options at the end of this article.

Add Custom JavaScript into your WordPress Site

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 using functions.php
  2. Add a script into select pages using a plugin such as Headers and Footers
  3. Embed a new Javascript file to your template (for all pages), such as for adding a 3rd party service such as Google Analytics using functions.php
  4. Use the script as part of the template's headeroutput

Add Javascript code to a single page only

This 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 conditios such as: 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:

 

 

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 load_js_script() {
  if( is_page(ID) ) {
    wp_enqueue_script('js-file', 'PATH_TO_JS_FILE', array('jquery'), '', false);
  }
}

add_action('wp_enqueue_scripts', 'load_js_script');

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.

Adding Javascript to WordPress 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 otion 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 "Header and Footer" 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:

<script src="http://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 other 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.

If you found this tip useful, you might want to check out more of our WordPress tips here

Adding Javascript to WordPress using functions.php

The easiest and cleanest method to add a javascript file to your WordPress theme is by using functions.php file with wp_enqueue_script.

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 my_theme_scripts_function() {

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

}

add_action('wp_enqueue_scripts','my_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()

 

Add JavaScript in Your Theme Header

In certain cases, you might want that the 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.

 

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="//cdn.collectiveray.com/scripts/myscript.js"></script>

Make sure that you have defined the type correctly, otherwise your site will not be valid.

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>

Need help getting stuff done? Try these affordable top-rated gigs on Fiverr!

The above 4 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 would like any help in getting this done, you may want to check out some of the cheap offers below:

fiverr logo

 

Click here to find experts on WordPress fixes.

Click here if you need to create a full WordPress website.

 

 

Download the list of 101 WordPress tricks every blogger should know

101 WordPress tricks

Click here to Download Now

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 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!

Featured On

Inc Magazine Logo  

Sitepoint logo  

CSS Tricks logo   

webdesignerdepot logo   WPMU DEV logo   

and many more!

 

 

Get Started Now With ShutterstockShutterstock

Best Rated Caching Plugin

Make your website faster 

How to make your website FAST!

Step-by-step - free email course, how to make your website load in less than 1 second 

 

Work with CollectiveRay.com

CollectiveRay (formerly known as DART Creations) is interested in developing partnerships with mutual benefit. If you like the stuff we publish and would like to develop a relationship, we'd be happy to hear from you. Go on - drop us a line - we'd love to hear from you :-)

 

Disclosure: CollectiveRay is funded personally out of a pure passion for helping people working with websites. We do however generate some income through recommendations of products. This means if you click on a link and purchase an item we link to, we will receive a small sum out of that sale. We usually partner with vendors to make your purchase cheaper than buying direct.

 

InMotion Hosting CollectiveRay Deal

who are we?

CollectiveRay is run by David Attard - working in and around the web design niche for more than 12 years, we provide actionable tips for people who work with and on websites. We also run DronesBuy.net - a website for drone hobbyists.

David attard