How to Add Your Own JavaScript to a WordPress Site

Need to add some extra functionality to your WordPress (WP) site? Then look no further. This guide will cover all the necessary steps to get your custom JavaScript working in WP.

This guide includes:

  • Setting up a Child Theme.
  • Using a File Manager.
  • Learning where to put custom JavaScript files.
  • Telling WordPress how to find and run custom files.

However, before we begin tinkering with anything, a word of caution:

Warning: Always backup your site before making changes to important files – even small mistakes can be disastrous.

Step 1 – Preparing the code

For this tutorial, I’ll be using a script that defers the JS of an embedded YouTube video.

Here’s the code:

%MINIFYHTML3dae652eacdde85a0a1b0822711de71417%
function init() { var vidDefer = document.getElementsByTagName('iframe'); for (var i=0; i<vidDefer.length; i++) { if(vidDefer[i].getAttribute('data-src')) { vidDefer[i].setAttribute('src',vidDefer[i].getAttribute('data-src')); } } } window.onload = init;

First things first, we need to make sure our code is saved as a JavaScript file. If you try using a plain text document, WordPress won’t be able to execute the script.

  • Copy & paste the code into your favorite editor (notepad is fine if you don’t have one).
  • Use the shortcut Ctrl + S or navigate to File -> Save As in the top left corner.
  • Save the file as a JavaScript format by adding .js to the end of your file name.

– OR –

  • Search for JavaScript under the Save As Type menu.
Screenshot of file system showing to save the JavaScript file as "my-scripts.js"

Make sure your file is saved as a .js format or it will not function properly.

Now that we’ve got a JS file saved, we’ll need to prep our site for it.

Step 2 – WordPress

Before we make any changes to our site, we’ll need to create a child theme. Without a child theme, any custom changes we make to the files of our website will be lost whenever we update the theme.

2.1 – Set up a child theme

Screenshot of showing to search for "child theme" and select the first option "child theme configurator"

To keep things simple, I highly recommend using the Child Theme Configurator (CTC) plugin.

  • Go to your Add New Plugins page.
  • Search “child theme.”
  • Install Child Theme Configurator (it should be the first option).

After installing CTC, go to Tools -> Child Themes and follow the prompts to set up your first child theme.

Screenshot of child theme configurator showing how to set it up.

Note: If you’re having trouble making a child theme, check out this guide from WordPress.org

2.2 – Get a file manager

Next, we’ll need a way to work with our website’s files. 

If you’re not comfortable with using an FTP program (or you have no idea what that is), then I recommend using the plugin WP File Manager (WPFM). It’s lightweight, easy to use, and best of all, you don’t have to leave your WordPress dashboard.

  • Go to Add New Plugins.
  • Search for “file manager.”
  • Install WP File Manager (it should be the first option).
Screenshot of plugins showing to download WordPress File Manager

Even though WPFM will be used for the remainder of this tutorial, you should be able to follow along with whichever you prefer.

Step 3 – Navigating your files & folders

Screenshot of wordpress file manager

Once you’ve installed a file manager of your choice, open it up and you’ll be presented with the main directory of your website.

Reminder: Don’t forget to backup your files before poking around in here. A small mistake can break your entire site!

Step 3.1 – Find your child theme

Screenshot of your website's files and how to navigate to your child theme.

Next up, we need to find our child theme’s directory. It should be something like this:

  • Wp-content > Themes > your-theme-child.

Keep in mind that not every site is the same, so you may have to look around to find the themes folder.

Step 3.2 – Create a js folder

Screenshot showing to create a folder named "js" in your child theme directory.

Once you’ve found the child theme, you’ll need to make a folder to hold your custom scripts.

  • Open the folder of your child theme.
  • Right-click anywhere in the empty whitespace.
  • Create a new folder called “js”.

Step 3.3 – Adding your custom JS file

Screenshot showing how to add the custom javascript file you made.

Now it’s time to add the JS file we created.

  • Open your newly created js folder.
  • Right-click anywhere on the empty whitespace.
  • Click Upload files
  • Navigate to the js file you created (my-scripts.js) and upload it.

Step 4 – Linking custom JS to WordPress

Unfortunately, we can’t just drop in some scripts and expect them to work. WordPress needs to be “hooked up” to your files before it can run them. To do this, we need to add a few lines of code to the functions.php file in your child theme directory.

First up, let’s look at the code we’ll be using.

Step 4.1 – WordPress Enqueue Script

function my_theme_enqueue_script() { wp_enqueue_script( 'my-scripts', get_stylesheet_directory_uri() . '/js/my-scripts.js' ); } add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_script');

To put it simply, the code above is telling WordPress where it can find the file “my-scripts.js” and to run it when the website loads.

Screenshot of previous code example.

Make sure the names in this code match the JS file you added previously. If the file’s name doesn’t match, WordPress won’t be able to find it.

4.2 – Adding the enqueue script to functions.php

Screenshot highlighting the functions.php file within the child theme directory

Now that we have the code to hook up our JS, we just need to add it to functions.php.

  • Navigate to your child theme’s main directory.
  • Look for a file called functions.php.
  • Right-click functions.php.
  • Select Code Editor to edit the file.

Once you have opened functions.php, copy the enqueue script mentioned previously:

function my_theme_enqueue_script() { wp_enqueue_script( 'my-scripts', get_stylesheet_directory_uri() . '/js/my-scripts.js' ); } add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_script');

Then, paste the script at the end of the file, after any existing code (if there is any).

Example:

screenshot highlighting where to place the code within the functions.php file (place it at the very end)

Note: Don’t worry if your functions.php file looks different. Depending on how you set up your child theme, there may not be any code at all, or just a few lines. Either way, it makes no difference – you just need to have a functions.php file.

If you don’t have a functions.php file, you can create one by right clicking on the page and selecting “New File”, then naming it functions.php.

Afterwards, your file should look something like this:

A screenshot of the completed functions.php file

Press Save & Close near the bottom right.

If all the steps were followed correctly, your scripts should now be running!

Q: What is the purpose of functions.php?

A: The functions.php file allows you to add more functionality to your site by using PHP code – much like a plugin does. That could be anything from creating a widget to adding a button, or even custom scripts.

The main difference between creating a plugin vs editing functions.php is that plugins can be reused in different themes, whereas functions.php is unique to each theme.

(Optional) How to apply JavaScript to a single post or page

Currently, our code will be running on every page of the website. If you only want your JS to run on a specific post, you’ll need to add a little bit of logic to the function, like so:

function my_theme_enqueue_script() { if (is_single ('post-id')) { // change 'post-id' to match your own post! wp_enqueue_script( 'my-scripts', get_stylesheet_directory_uri() . '/js/my-scripts.js' ); } } add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_script');

Here we’ve placed the wp_enqueue_script inside of an if statement. This will make it so our code checks to see if the correct post is being viewed before running.

For this script to work, you need to change the 'post-id' text to match your own site’s post ID. Make sure to keep the quote markers!

Keep in mind, the above example will only work on specific posts of your site. To set a specific page, you can change the is_single text to be is_page instead.

function my_theme_enqueue_script() { if (is_page ('page-id')) { // change 'page-id' to match your own page! wp_enqueue_script( 'my-scripts', get_stylesheet_directory_uri() . '/js/my-scripts.js' ); } } add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_script');

Just like with post-id, you’ll need to modify the page-id to match your own page ID.

Step 5 – Test Your Site

Last but not least, it’s time to do some testing! Spend a few minutes and go through this task list:

  • Test the specific thing your scripts are doing.
  • Browse multiple pages on your site.
  • Test the functionality of your site (such as buttons, search, etc…)
  • Don’t forget to clear your website’s cache.

Typically most errors will be apparent right away – but not always. It’s important to be thorough and make sure everything is working correctly.

Wrap Up

Congrats! In addition to adding JavaScript to a WordPress site, you can now:

  • Create a custom JavaScript file.
  • Create a child theme.
  • Add folders and files to a WordPress site.
  • Use PHP to run a custom file in WordPress.

If you’re still having trouble or have any questions, send me an email at [email protected] – I’m happy to help!

Dakota

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.