How to Add Custom JavaScript to Your WordPress Site

How to Add Custom JavaScript to Your WordPress Site

If you want to enhance your WordPress site’s front-end functionality, you’ll need to add JavaScript to your site—whether you’re using a third-party library or a custom script. Based on your goals and coding knowledge, you can choose from a couple of techniques to add custom JavaScript to WordPress, from using plugins to attaching custom scripts to different action hooks. 

In this tutorial, we’ll look into each method, see how they work, and when you should use which one.

  • WordPress
    How to Add Custom CSS to Your WordPress Site
    Anna Monus
  • WordPress
    How to Create a WordPress Child Theme
    Rachel McCollin
  • WordPress
    How to Remove “Powered by WordPress” From the Footer
    Jessica Thornsby

Adding Custom JavaScript to WordPress

While you can use WordPress’ built-in Customizer to add custom CSS to your theme, you can’t do the same with JavaScript. To add custom JavaScript to your WordPress site, you need to either use a plugin or edit your (child) theme’s functions.php file. We will have a look at both option in detail, but here’s a short summary.

1. You can use different types of plugins to add custom JavaScript to WordPress: 

  • plugins for editing the header and footer templates
  • plugins for adding custom JS code to WordPress
  • script-specific plugins for adding and configuring third-party scripts such as Google Analytics or AdSense

2. Or you can use WordPress functions and hooks in the functions.php file:

  • the wp_head and wp_footer action hooks
  • the wp_enqueue_scripts , admin_enqueue_scripts , and login_enqueue_scripts action hooks
  • the wp_enqueue_script() WordPress function

One Thing You Should Never Do

Even though the easiest way to add a custom script to your WordPress site is by dropping a <script> tag directly into either your header.php or footer.php template file, you should never do so. This is because WordPress has a specific loading sequence that should be respected under any circumstances. 

If you insert your custom JavaScript directly into your header or footer template, it might cause conflicts with your theme, plugins running on your site, or the WordPress core. Instead, you should use one of the techniques detailed in this article. 

So, never add a line like the following line to your header.php or footer.php file (even if you could technically do it):

1. Use a Plugin to Add Custom JavaScript to WordPress 

Using a plugin is the recommended method when you:

  • don’t want to directly edit the source files,
  • want to add theme-independent JavaScript that you can keep even when you decide to switch to a new theme.

You can use different kinds of plugins to add custom JavaScript to your WordPress site.

1.1. Plugins for Editing header.php and footer.php

The first option is to use a plugin that lets you edit the header and footer template files of your WordPress theme. If you want to add scripts that load before the page content, such as analytics and tracking scripts, you need to edit the header template, while scripts that load after the content go into the footer template. Typically, when your script modifies an element displayed on your page, such as an image gallery script, it should be placed into the footer.

Insert Headers and Footers is a good example of a plugin that allow you to edit header and footer templates. It has a simple user interface with just two text areas—one for the header and one for the footer scripts. It adds your scripts to either the wp_head or the wp_footer action hooks. 

You can insert any kind of script into the two input fields. You need to enclose your scripts with the <script></script> tag. Besides, you can also use this plugin to add custom CSS to your header template, you only need to enclose it with the <style></style> tag (note that CSS should always be added to the header).

Insert Headers and Footers plugin for WordPress

1.2. Plugins for Adding Custom JavaScript 

Another option is to opt for a plugin that allows you to add custom JavaScript to your WordPress site. These plugins are very similar to header and footer editing plugins, and most of them also use the wp_head and wp_footer action hooks. However, they usually provide you with more configuration options.

For instance, the Simple Custom CSS and JS plugin lets you define the permalink for your custom JavaScript files, save them into the wp-content/ folder, manage your scripts as a custom post type, and more. If you want to add multiple custom JavaScript files to your WordPress site and keep them organized, you will find this type of plugins very useful.

Custom CSS and JS plugin

1.3. Script-Specific Plugins

Finally, if you want to add only one third-party script to your site, you can also check if it has an integration plugin for WordPress. Creators of popular third-party JavaScript libraries frequently publish a free plugin in the WordPress.org repo so that you can easily add their tool to your site. The biggest advantage of this kind of plugins is that they come with built-in configuration options for that specific JavaScript library.

For example, the popular GA Google Analytics plugin lets you add Google Analytics to your site right from the WordPress admin area. It comes with built-in features that are specific to the Google Analytics script, such as enhanced link attribution, IP anonymization, custom tracker objects, and others.

GA Google Analytics plugin for WordPress

2. Edit Your Child Theme’s functions.php File

Besides relying on plugins, you can also use WordPress’ built-in functions and action hooks to add custom JavaScript to your site. In this case, you need to edit your functions.php file and upload the scripts manually to your server. It’s also advisable to create a child theme for your customizations so that you can securely update the parent theme without losing the custom code. You can upload your custom scripts to your child theme’s root folder or, if you have more than one script, you can create a scripts folder for them.

You need to add the PHP code that enqueues or prints out your custom JavaScript to your child theme’s functions.php file. You can edit this file either in your code editor and upload the updated version manually to your server, or via the Appearance > Theme Editor menu of your WordPress admin area (see on the screenshot below).

WordPress Admin Theme Editor

2.1. Enqueue Your Custom Scripts with the wp_enqueue_script() Function

The WordPress Theme Handbook recommends the wp_enqueue_script() function to add custom scripts to your site. This built-in function respects WordPress’ loading sequence and enqueues your custom scripts in the proper order, so they won’t conflict with other scripts loaded by the WordPress core and plugins running on your site.

With wp_enqueue_script(), you can add your custom JavaScript both to the header and footer templates. By default, it enqueues the scripts in the <head> section of the page loaded by the header template. 

If you want to add your script to the header, you only need to define a custom handle ('custom' in the example below) and the path to the script. As you can see below, I’ve also used the get_stylesheet_directory_uri() WordPress function to get the URI of the child theme directory. And, the add_action() function adds the custom tutsplus_enqueue_custom_js() function to the wp_enqueue_scripts action hook that lets you enqueue custom scripts you want to display on the front-end of your site.

Beware that although the wp_enqueue_script() built-in WordPress function and the wp_enqueue_scripts action hook have almost the same name, they are different things.

Besides enqueuing scripts for the header, you can also use the wp_enqueue_script() function to add custom JavaScript to the footer template. However, in this case, you also need to define all the optional parameters, respectively: 

  1. the dependencies–array() as we have no dependencies for now,
  2. the version of the script–false as we don’t want to add version numbers,
  3. whether this is for the header or footer template–true as we switch to the footer template which is the non-default option.

If your custom script has dependencies, you need to add them to the array() parameter of the wp_enqueue_script() function. There are a couple of popular scripts and libraries, such as jQuery, that are already registered by the WordPress core, so you can add them using their registered handle ('jquery' in the example below).

If you have a dependency that is not registered by WordPress, you need to register and enqueue it with another wp_enqueue_script() function, before you can add it as a dependency using its custom handle.

If you want to run your script in the admin area instead of the front-end of your site, you need to use theadmin_enqueue_scripts action hook instead of wp_enqueue_scripts in the add_action() function. And for the login screen, you need to use the login_enqueue_scripts action hook that enqueues custom scripts only for the login page. 

2.2. Print out Your Inline Script with the wp_head or wp_footer Action Hooks

Although the WordPress documentation recommends using the wp_enqueue_script() function for custom scripts, you can also add inline scripts to your site with the wp_head and wp_footer action hooks. Instead of enqueuing your custom scripts, these hooks only print them out in either the header or footer template. So, you should only use this technique to add inline scripts, but not for external .js files.

This is how you can use the wp_head action hook to print out an inline script in the header template:

And, this is how you can use the wp_footer action hook to print out an inline script in the footer template:

As wp_head and wp_footer only fire on the front-end of your site, scripts added with these hooks won’t load in the admin area and login page. To add custom inline scripts to your admin area, you should rather use the admin_head and admin_footer action hooks in the add_action() function. And, if you want to print out scripts on the login page, use the login_head and login_footer action hooks.

Note that the aforementioned plugins (Insert Headers and Footers and Simple Custom CSS and JS) do use wp_head and wp_footer not only for inline scripts but also for external .js files, but you still shouldn’t do the latter unless you really know what you are doing. This is because the plugins run extra checks that make sure that WordPress’ loading sequence is respected. If you want to add your custom scripts manually, it’s much safer and easier to stick to the recommended wp_enqueue_script() function.

Wrapping Up

You can add custom JavaScript to your WordPress site by either using a plugin or editing your theme or child theme’s functions.php file. 

Using a plugin is the recommended technique if you don’t want to edit your source files, as these plugins ensure that your custom scripts load in the right order. Enqueuing your scripts in the functions.php file manually allows you to tie your custom scripts to your theme and keep everything in order without having to add another plugin to your WordPress site.

The Best WordPress Themes and Plugins on Envato Market

Explore thousands of the best WordPress themes ever created on ThemeForest and leading WordPress plugins CodeCanyon. Purchase these high-quality WordPress themes and plugins can and improve your website experience for you and your visitors. 

Here are a few of the best-selling and up-and-coming WordPress themes and plugins available for 2020.

  • Inspiration
    15+ Best WordPress Portfolio Themes for Creatives
    Brenda Barron
  • WordPress
    17 Best WordPress Slider & Carousel Plugins of 2020
    Daniel Strongin
  • WordPress
    20 Best WordPress Calendar Plugins and Widgets
    Daniel Strongin
  • WordPress Themes
    23+ Best Responsive WordPress Themes (For Sites in 2020)
    Brenda Barron
  • WordPress
    24 Best WPBakery Page Builder (Visual Composer) Addons & Plugins of 2020
    Daniel Strongin
  • WordPress Themes
    20+ Best Coaching & Consulting WordPress Themes (2020)
    Brenda Barron

Go to Source
Author: Anna Monus