Search

How to Add Custom JavaScript in WordPress (without Plugin)

Adding custom JavaScript to a WordPress website is one of the best methods to improve both functionality and appearance, particularly for those who opt against installing too many third-party plugins on their website.

JavaScript, being a versatile scripting language, is primarily employed in client-side web development. It empowers the addition of dynamic and interactive features to web pages, offering a flexible means of customization.

If you have JavaScript code ready but are unsure where to place it in WordPress, this tutorial will guide you through various methods without the need for third-party plugins. Feel free to jump directly to the method of your preference. Let’s explore these options together!

Adding Custom JavaScript in WordPress

Method 1: Using the Theme’s functions.php File

Adding custom JavaScript directly within your theme functions.php file is one of the quickest methods in WordPress. However, speed doesn’t always equate to safety, as your changes may be lost during theme updates. It’s advisable to create a backup of your WordPress files, either through backup plugins or your built-in backup feature of your hosting service. Despite this caveat, this method is often preferred for a swift solution to your specific requirements.

To access the functions.php file, go to AppearanceTheme File Editor on your WordPress admin dashboard (under the Tools menu if you’re working with a block theme) and select the file from the theme file list. However, avoid directly pasting JavaScript into the functions.php file. Instead, utilize predefined functions in WordPress.

We offer several function templates that utilize these predefined functions, providing a designated space for you to insert your custom JavaScript code.

Apply the Code to the <head> Section of the Website

Add your custom JavaScript in the following function that utilizes the wp_head action hook to apply the code throughout your entire website via the header.

function wpp_customjs() {
    ?>

    <script>
        //paste the code here
    </script> 

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

Below is the illustration of the code placement using the above function on the theme file editor.

If you noticed from the screenshot above, we prioritize loading the jQuery library first, as our script relies on jQuery code.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

Another instance where loading the jQuery library is necessary can be found in our previous article about creating a testimonial slider in Gutenberg. However, if your script doesn’t require it either because it doesn’t use jQuery or the library is already enqueued by your theme then you don’t need to load the jQuery library.

Apply the Code to the <footer> Section of the website

Just like the head section, you can add your custom JavaScript inside the following function that utilizes the wp_footer action hook to apply the code throughout your entire website via the footer. The hook is commonly used for enqueuing scripts that need to be loaded after the main content, enhancing performance.

function wpp_customjs() {
    ?>

    <script>
        //paste the code here
    </script> 

    <?php
}
add_action('wp_footer', 'wpp_customjs');

Utilizing the wp_enqueue_script Function

The wp_enqueue_script()function ensures proper handling, dependency management, and loading of your scripts. Here’s an example of how to use it:

   function wpp_custom_script() {
       wp_enqueue_script('custom-script', get_template_directory_uri() . '/js/custom-script.js', array('jquery'), '1.0', true);
   }

   add_action('wp_enqueue_scripts', 'wpp_custom_script');

Explanation of the parameters:

  • 'custom-script': This is the handle for your script. It should be unique.
  • get_template_directory_uri() . '/js/custom-script.js': The path to your JavaScript file.
  • array('jquery'): An array of script handles that your script depends on. In this example, it depends on jQuery.
  • '1.0': The version number of your script. Update this when you make changes to ensure browsers fetch the latest version.
  • true: Indicates whether to load the script in the footer. Setting it to true is a common practice for performance optimization.

The wp_enqueue_script() function in WordPress is primarily designed to enqueue external JavaScript files. However, if you find the need to include inline JavaScript directly, you can refer to our previous article on adding an external link icon to external links for a practical example.

Method 2: Create a Custom Plugin

Another approach to add JavaScript code is by creating a custom plugin. Contrary to what it may sound, creating a plugin is a straightforward process. At a minimum, it requires a main PHP file and a JavaScript file for your code.

If you’re interested in developing your plugin, refer to our previous article on safe ways to add custom code to WordPress for a comprehensive guide.

After creating the main PHP file and the JavaScript file with your JavaScript code in it, incorporate the following function in the main PHP file. This function utilizes wp_enqueue_script to load the JavaScript file.

function custom_plugin() {
    wp_register_script('custom-script', plugins_url( '/', __FILE__ ) . '/js/custom-script.js' );
    wp_enqueue_script('custom-script');

}
add_action('wp_enqueue_scripts', 'custom_plugin');

Replace ‘js/custom-script.js‘ with the actual folder and filename of your script. After installing and activating your plugin, your custom script will also be activated.

Need a practical example about creating your own plugin that utilizes a JavaScript file? you can read our previous article about adding a copy to the clipboard button for Gutenberg code block.

Method 3: Use a Child Theme

The third method is to use a child theme to add custom JavaScript to your website. Either you create a new one or use a premade child theme, if you’re making frequent customizations, it’s recommended to use a child theme. If you’re interested in creating one, you can read our previous article about creating a child theme.

When you have your child’s theme ready, follow these instructions:

  1. Add Custom JavaScript in Child Theme:
  • Create a JavaScript file (e.g., custom-script.js) in the child theme directory either via SFTP or your hosting file manager.
Custom JavaScript in a WordPress Child Theme via SFTP
  • Enqueue the following script in the child theme’s functions.php file, before the closing of the PHP tag (?>):
php function enqueue_custom_scripts() { 
    wp_enqueue_script('custom-script', get_stylesheet_directory_uri() . '/custom-script.js', array('jquery'), null, true); 
} 
    
add_action('wp_enqueue_scripts', 'enqueue_custom_scripts');
  • Replace the ‘/custom-script.js‘ from the code above with your actual custom JavaScript file name.
  1. Write Your JavaScript Code:
  • Add your custom JavaScript code to the custom-script.js file.
  1. Save Changes:
  • Make sure to save the changes to both the functions.php file and the custom.js file.

The Bottom Line

Adding custom JavaScript to your WordPress website provides an optimal avenue for enhancing both functionality and aesthetics, especially for those averse to an abundance of third-party plugins. This tutorial has guided you through various methods, all without the necessity of installing any third-party plugins.

This page may contain affiliate links, which help support our project. Read our affiliate disclosure.
Hendri Risman

Hendri Risman

Hendri is a WordPress expert and a writer staff at WPPagebuilders. He writes solutions on how to get things fixed in WordPress a lot. Mostly without involving a plugin.
Want to save yearly expense up to $219? why not?

Leave a Comment