Add Javascript To WordPress Site - 7 Step-By-Step Methods

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 third 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 learn how to recruit the best WordPress developer for your business or 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

What is JavaScript?

If you’re reading this post, you’re probably already familiar with what JavaScript is.

However, to keep it accessible to everyone, we’ll quickly outline what JavaScript is and what it does. Feel free to skip this part if you already know.

JavaScript is a programming language that runs in a browser. It can be called from the web server but runs within the visitor’s browser.

This provides quite a lot of scope for making it do cool things like embedding video and adding functions.

For example, you can use JavaScript to embed a video player so your web server doesn’t have to do it.

This improves the user experience by including video, without adding burden to your web server to play the video.

JavaScript is also used in mobile apps, games, server applications, front-end development and, more recently, AI-related development.

Can you use JavaScript in WordPress?

Yes, you can use JavaScript in WordPress. Given the inherent flexibility of the CMS, you can use JavaScript to add interactive elements or place third-party APIs on a page.

The uses are many and varied but as JavaScript is run by the user’s browser, it can do a lot without slowing down your web server.

You can add script in a number of ways as we’ll discuss in a little while.

Before making any changes to files, we would recommend creating a child theme and/or backing up your website first.

You can’t be too careful!

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 JavaScript to All Pages
  4. Add a Javascript file to your theme header
  5. Using the wp_head Hook To Add Custom JavaScript
  6. Add JavaScript to your WordPress footer
  7. Adding JavaScript to WordPress Video
  8. Add JavaScript to a WordPress widget

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

Then we'll quickly share how to debug JavaScript once you have added it to a page.

Note: Some of these techniques involve making changes to core files. While it isn't usually a good idea to change functions.php and other core WordPress files, we want to show you all the ways to add code.

We don't necessarily recommend making changes this way but we beleive in giving you all the information and then making your own decision.

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.

We recommend using a plugin for all code changes as it keeps everything clean and can avoid any issues down the road.

Instead of modifying the theme's files directly with the custom Javascript code, a 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 add JavaScript to WordPress!

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. Add JavaScript to a specific WordPress 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

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 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');

3. 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

4. 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 third party script to 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>

4. 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.

Adding JavaScript to your WordPress footer is relatively simple. You can add code to the header or footer file, use a custom code element within your page builder or theme or use a specific header and footer plugin.

Add JavaScript to your WordPress footer

As you should avoid adding JavaScript to your header.php or footer.php files, we’ll use a plugin.

I recommend the WPCode – Insert Headers and Footers + Custom Code Snippets plugin.

Select Settings and the Insert Headers and Footers menu.

Then paste your JavaScript code into the footer section on the page.

Save your changes when you’re done.

IMH

Do you want a fast website?

Who am I kidding? Don't we all?

So why do so many of us struggle?

The biggest challenge is usually finding a fast, reliable hosting company.

We've all been through the nightmares - support take takes forever or doesn't resolve our problem always blaming something on your side... 

But the biggest bummer is that the website always feels slow.

At CollectiveRay we host with InMotion hosting and our website is stupid fast. We run on a custom stack of LightSpeed server setup on MariaDB with a PHP7.4 engine and fronted through Cloudflare. 

Combined with our front-end optimizations we reliably server 6000 users every single day, with peaks of 50+ simultaneous users. 

Want to get a fast setup like ours? Transfer your site for free to InMotion hosting and get our 50% OFF on current pricing.

Try InMotion Hosting with 50% OFF for CollectiveRay visitors in November 2024 ONLY!

InMotion hosting 50% OFF for CollectiveRay visitors

6. Adding JavaScript to WordPress Video

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

7. Add JavaScript to a WordPress Widget

If you want to add some JavaScript into a WordPress widget, it couldn’t be easier.

Add a widget, select the menu and select Edit as HTML.

Add your JavaScript within <script> tags and select Update.

The code you added should be instantly visible when you view the widget on the front end of your site.

How To Debug a JavaScript Error on a WordPress Page

Debugging JavaScript is a time-consuming process but is inevitable for beginners.

Fortunately, you have the tools on hand to check for errors.

Open a page in your browser and hit F12 or select Developer tools from the menu (Chrome). You can also use Ctrl + Shift + J (Windows/Linux) or Cmd + Option + J (Mac).

Select the Console tab of the new part of the screen that opens and you’ll see any JavaScript errors highlighted in red.

Identify where the error is coming from and correct the relevant part of the JavaScript you added.

Work your way through until all errors have been addressed.

WordPress has its own debugging mode but it can be a little complicated to use. I would recommend checking out the official debugging page for more information.

Frequently Asked Questions About Add Javascript to WordPress

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
David has been working in or around the online and digital industry for the last 21 years. He has vast experience in the software and web design industries using WordPress, Joomla and niches surrounding them. He has worked with software development agencies, international software companies, local marketing agencies and now is Head of Marketing Operations at Aphex Media - an SEO agency. 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. His blend of technology expertise combined with a strong business acumen brings a competitive edge to his writings.

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