How to Add Custom JavaScript to WordPress

WordPress is far and away the most popular content management system (CMS) in the world today. More than 450 million websites currently use WordPress to ensure smooth, efficient loading, effective, glitch-free navigation, and to provide clean, smart-looking designs. But as feature-rich and easy to use as WordPress is, it cannot possibly account for every function required by every website. The people behind WordPress understand this and leave room for developers to add their own unique functionality by way of custom javascript.

Adding Custom JavaScript: What is It and When to Use It

Before we get into the details of adding custom javascript to a WordPress site we need to take a quick look at JavaScript, what it is, and when it should be used.

What is JavaScript?

How to add custom JavaScript to WordPress

JavaScript is a kind of everyman’s programming language. By that we mean you won’t be able to use it to program a deep space probe to analyze soil samples harvested from the surface of Mars. But you can use it for things like form validation on a web page.

JavaScript can trace its origins to the early 1990s and the advent of the first widely successful web browser, Netscape Navigator. The people behind Netscape wanted a way to add dynamic elements to web pages that were uniformly static at the time.

The result was LiveScript, whose name was changed shortly after its release to JavaScript. JavaScript is often confused for Java, a more robust programming language that was very much in favor in the early 90s. But the two have little in common.

When to Use Custom JavaScript

As was the case 25 years ago, developers today use custom JavaScript to create new, or enhance existing website functionality. Typically, JavaScript is the last “layer” of programming commands read by a browser after HTML and CSS (cascading style sheets). As such, it adds, what is in effect, the icing on the web page cake.

That “icing” can take several forms. For instance:

  •  A site owner may want an information box to appear when a user scrolls over a certain piece of text. That’s called an “event”, and custom JavaScript can make it happen.
  • Or they may need to store values entered into a website form box for the purposes of validation. Custom JavaScript is often used to do this.
  • These days JavaScript is commonly employed to detect the type of device a person is using to access a website (a PC or mobile device) so that the proper version of the site can be served.
  • Another very common use of custom JavaScript these days is to create popups that prompt the user to subscribe to a site, or to be notified when new content is posted.
  • In some cases, websites will employ custom js in WordPress to produce what is called an “application programming interface”, or API. One example of an API would be providing a user with the ability to manipulate an audio clip that is embedded on a web page.

This is hardly a comprehensive list of the many ways developers employ custom JavaScript these days. But it should give you a good idea of just how common the practice is. If you have any experience surfing the web you have no doubt encountered most or all of the above at one time or another.

The Right and Wrong Ways to Add Custom Javascript to WordPress

How to add custom JavaScript to WordPress

Now that we have a better idea about what JavaScript is, and how JavaScript is used to enhance the web experience, let’s take a look at the right way and the wrong way to add it to a website.

First Things First: The Wrong Way

Adding a custom script may well be necessary to achieve the functionality a business owner is after. But if the script is added in a rushed or haphazard fashion it could wind up doing far more harm than good. In order to save time and trouble, it’s best to first address the ways custom js in WordPress should not be deployed, before getting into the right way to do so.

Whenever Possible Do Not Add JavaScript to Header.php

The simplest way to add JavaScript to a webpage is to add it to the “header.php” WordPress file. This is also the simplest way to cause WordPress dysfunction that will require professional website repair. That’s because, while WordPress is an incredibly reliable and versatile vehicle for producing state of the art websites, the order in which it loads page elements is pretty much set in stone.

We alluded to this above when we described custom js for WordPress as the icing on the webpage cake. In other words, the last item in the loading sequence. If a developer upsets the established loading sequence by dropping a JavaScript into the header.php file it can throw a wrench into that loading sequence. That can cause a cascade of effects, none of which are particularly good.

The same applies to the “footer.php” and “template.php” files. Adding JavaScript code into those files may cause a rash of unexpected and unwanted effects. In addition, if you add custom js to WordPress PHP files directly, those scripts will be lost if the theme undergoes an automatic update.

Finally, keep in mind too that even if the negative effects of placing JavaScript directly into the header.php or template.php files are not blatantly obvious, Google’s web bot may pick up on them and flag the site as problematic. This can do significant harm to the ranking of the page in organic search results. And that is the ultimate no-no.

The Right Way to Add Custom JS to WordPress

Now that we know how not to add custom JavaScript to a WordPress site let’s take a look at the proper way to do it. Since adding js directly to the PHP files is not recommended you’ll need to either A) create separate JavaScript files and tether them to the existing website framework, or B) use one of the many WordPress plugins designed specifically for the purpose of adding custom JavaScript.

Note: Before we go any further we should also emphasize the importance of creating a “child theme for your site and making any modifications to that. This will ensure that if anything goes terribly wrong that you have a complete backup of the site ready to step in.

Method A: Creating Separate JavaScript Files

This method of adding custom js to WordPress has a long history and is considered safe and effective (as long as the person creating the scripts knows what they’re doing, of course). Whatever functions you want to add to a particular page should be clearly defined in the separate JavaScript file. Once the file is complete and named you will add it to the appropriate directory of your website and add a call line in the head of the page you want to modify with the script. That call will look something like this:

<script type="text/javascript" src="https://file.belovdigital.agency/scripts/whatever.js"></script>

When the page loads it will read this call and reach out to the “whatever” file to execute the scripts that are there. If those scripts are well-formulated they should execute flawlessly on the page and enhance the functionality. If you are not sure how to add the call to the header of the page there are plugins that will do it for you.

Method B: Using a WordPress Plugin to Add Custom JavaScript to WordPress

How to add custom JavaScript to WordPress

WordPress and plugins go together like apples and cinnamon, or peanut butter and jelly. You really can’t fully appreciate one without the other. By current estimates, there are more than 55,000 plugins in the official WordPress repository, and tens of thousands of non-official plugins loitering around the internet hoping someone will take a liking to them.

With that many plugins, it’s reasonable to assume that there might be one or two out there designed to produce the event or effect you’re after. All you have to do if you’re developing a WordPress website is log into the site via the “yoursite/wp-admin/” login interface, navigate to the plugin page and enter the function you’re looking for in the search box at the top of the page.

You’ll then be presented with a host of plugins all designed to produce the desired effect, event, API or whatever. Select one and click “install”. Then click “activate” and fill in whatever variables may need to be filled in to complete the process. Using a plugin has several advantages.

  • First, if the plugin is in the WordPress repository you know it has been thoroughly vetted and is both safe and effective.
  • Second, if you are developing a site yourself and you are not a professional coder, you will not have to hire one to get the effects you’re after. That can save you a lot of money.
  • And third, adding functionality via plugins is so quick it’s a little bit ridiculous.

Examples of JavaScript-Related WordPress Plugins

As we said, there are a multitude of WordPress plugins available for just about every imaginable function, event, or other process or effect. Though they tend to take different paths to the same destination. Let’s look at a few of the methods these plugins for WordPress use to work their magic.

Plugin to Add a Call to a Custom JavaScript File

This is the method we would recommend for adding custom JavaScript functionality to a website or web page. It separates the JavaScript from the PHP thereby dramatically reducing the chance that there will be an unresolvable conflict between the two. 

Locating such a plugin is typically a straightforward affair. Just log in to the website through the admin page. From the dashboard go to the plugin page and search for “add custom JavaScript”. Numerous plugins should be presented to you.

Because terminology often overlaps and is used to define different processes, make sure the plugin you choose is one that will enable you to define a permalink to the appropriate JavaScript file.

In most (not necessarily all) cases, you will upload your js file via FTP to the wp-content/ folder. And your plugin should allow you a way to enter the permalink to that file, which will then be added to the header or footer.php files as a call, rather than as lines of executable code.

Plugin to Add a Single Specific JavaScript to Your WordPress Site

Sometimes all a developer wants to do is add a single JavaScript script to a single page. If that script has been created by a third party there may well be a WordPress plugin you can install that will integrate the script seamlessly and effortlessly into your site.

It may seem a bit far-fetched that anyone would go to the trouble of creating a plugin just to integrate one lonely piece of js into a single page on a website, but it’s not at all. Coders who create custom js for WordPress will often produce an accompanying plugin to facilitate the use of the script and enhance their reputation. 

Plugin to Add JavaScript to the Header or Footer PHP Files (Not Recommended)

Finally, although we started out saying you should never add JavaScript code directly into the header.php, footer.php or template.php files there are some who nonetheless insist on doing so. For them, we would say if you feel the overwhelming compulsion to add JavaScript to the WordPress PHP files, at least use a plugin to help with the process. 

A plugin will make it less likely that the code you add will create cascading problems that could undermine your site’s functionality, as well as its viability in the eyes of Google. Keep in mind that if you want to add a script intended to execute before other page content, you’ll need to add that to the header.php file. And if you want to add a script designed to execute after the other page content has loaded, you’ll need to add it to the footer.php file.

There are numerous plugins out there that will perform these modifications of the PHP files for you. Simply search for them on the plugins page of your site and then install, activate and open the plugin interface. There you’ll be asked to enter the script (or scripts) that you want to execute. Some of these plugins include a box for entering script(s) into the header and a separate box for adding script(s) to the footer. You can choose to leave either blank or you can add scripts to both PHP files simultaneously.

We’re just going to reiterate one more time that we do not recommend adding custom JavaScript directly to WordPress PHP files. But instead, create a separate JavaScript file or use a plugin that creates that file for you and then modifies the header or footer.php file to call that separate js file.

Conclusion

WordPress is, without a doubt, the world’s most popular content management system. It earned that distinction by being easy to use, reliable, versatile and customizable. But there are right ways to add custom JavaScript to a WordPress site and there are wrong, (or at least less desirable), ways to do so.

Use the information provided in the above guide to determine which method of adding custom js to a WordPress site is right for your particular website, or the site you are developing for someone else. And remember these fundamental rules:

  •  Always create a child theme and make any modifications to that.
  • Don’t add JavaScript directly into the WordPress PHP files if you can help it.
  • Use a plugin to help ensure your JavaScript additions don’t cause problems with your WordPress site.

Good luck!

Comments

Leave a Reply

(Your email address will not be published)