Add Javascript To WordPress Site - 3 Easy Ways (Posts/Pages)

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 break your website, or create a performance bottleneck.

Adding Javascript to WordPress pages and posts directly is not possible, so 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. 

If you are in a hurry, use the table of contents below to scroll to the relevant part of the article.

 

This article includes changes in WordPress code. 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 a script into select pages using a plugin such as WPCode
  2. Add the script to a specific or single page of your choice, or multiple pages using functions.php
  3. Add a Javascript file to your theme header

Let's go through each of these methods in detail.

1. Use a plugin such as WPCode

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

As the name says it allows you to add small pieces of code such as scripts to the header and footer files which is were they need to be most of the times. 

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 several different options so we'll just describe the most common ones you will need to use.

You can download WPCode here or install it using the Install Plugins function of WordPress.

Install the WPCode plugin:

  • Log in to your site's backend or admin.
  • Go to Plugins > Add new
  • Search for "WPCode" plugin and click on Install Now.
  • Once it has installed, click on Activate

install wpcode

 

You can now either load a custom script without a file (e.g. to add a script that you've been given such as Google Analytics) or upload a custom Javascript file. 

The most common option you can use with this plugin, is the option to the add the code directly into WordPress.

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 Global Header and Footer window.

You can choose to add the script to Header, Body or Footer. You should have guidance from the provider of the script into which of these sections you need to add the script.

Let's say you want to add it to the Header:

adding javascript code to wordpress header

Click "Save Changes" to finish.

The WPCode plugin will now add the code to each page of your website.

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.

WPCode also allows you to create your own code snippets.

You can also insert code snippets anywhere on your website, such as inside posts or pages, before or after a post, before or after content, or a number of other options which you might need.

Simply navigate to Code Snippets > Add Snippet and then select 'Create Your Own.'

add your custom code

You will now be taken to a 'Create Custom Snippet' page where you may give your code a title and paste it into the 'Code Preview' box.

create custom javascript snippet

Then, from the 'Code Type' dropdown menu, pick 'JavaScript Snippet.'

javascript snippet

Then, simply scroll down until you reach the 'Insertion' area.

All that remains is to choose a 'Location' for the code from the dropdown menu. Locate 'Page, Post, Custom Post Type' and specify where you want the code to display on the page or post.

If you want WPCode to put the snippet before or after a paragraph, you can specify which paragraph in the post it should appear before or after.

If you enter 1 in the 'Insert Number' field, for example, the code snippet will appear before or after the first paragraph. For the second paragraph, use 2, and so on.

After that, simply toggle the toggle near the top of the screen to 'Active,' and then click the 'Save Snippet' option beside it.

That's all it takes to get your code sample online!

The main advantage of using a plugin is that it is a beginner-friendly option. You don’t need to worry about editing your theme’s files. The WPCode plugin also might come in handy if you’re looking for a seamless way of adding other types of code and custom CSS.

However, the downside of this method is that it involves installing a third-party plugin, which some site owners try to avoid. If you want to keep your extensions to a minimum, you might be better off using one of the other methods.  

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

 

2. 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:

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


Using this method you do not need to install another plugin if you edit your functions.php file. This method can also be used to add features and functionality to both your theme and WordPress itself. This approach, for example, can install JavaScript into a single post or page or all pages.

The main disadvantage of this strategy is that it requires you to deal with code and update your website's files. As a result, if you lack experience in this field, it may not be the ideal alternative.

fiverr logo

Click here to find cheap experts on WordPress fixes

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>

 

Using the wp_head hook to add custom JavaScript


You can also add custom JavaScript to your header using the wp_head action hook. Again, this solution is not preferred because it generates an excessive number of scripts. It is, nevertheless, preferable to manually inserting the scripts into your header.php file.

This method, which may also be used for the footer, makes use of the action hook(s) to insert inline scripts into your site. Unlike the wp enqueue script function, which enqueues custom scripts, the wp head method prints the scripts in your header template (and footer, if you use the wp_footer hook).

To begin, navigate to your functions.php file and copy and paste the following code:

function collectiver_custom_javascript() { ?>

<?php } add_action('wp_head', 'collective_custom_javascript');

 

It's worth noting that the wp head hook only works on the front end of your website. This implies that any custom JavaScript added through this approach will not appear in the admin or login areas. However, if you wanted to add JavaScript to those locations, you could do so by using the admin head and login head action hooks.


Developers like the wp enqueue script function because it avoids conflicts that can occur with other solutions, such as directly adding scripts to your header.php file. Furthermore, this solution does not generate any dependant scripts.

The major issue with adding custom WordPress JavaScript to your site's header is that it can interfere with other plugins that load their own scripts. This configuration can also cause several scripts to load multiple times, which might slow down your website's overall speed and performance.

Download the list of 101 WordPress tricks every blogger should know

101 WordPress tricks

Click here to Download Now

Adding Javascript to WordPress Video

Want to see how to add Javascript to WordPress on a YouTube video? This is a good watch:

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.

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, but 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.

(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.)

Frequently Asked Questions

What is Javascript?

JavaScript is a computer language that executes in the user's browser rather than on your server. Client-side programming enables developers to achieve a variety of interesting things without slowing down your website. You may frequently be requested to copy and paste a JavaScript code snippet into your WordPress website if you wish to embed a video player, add calculators, or some other third-party service.

How do I add a Javascript file to WordPress?

The easiest way to add a Javascript file to WordPress is using the Insert WPCode plugin. 

  • Log in to your site's and install WPCode 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 WPCode
  • 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 WPCode 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 ...