How to Add JavaScript to WordPress Using a Plugin and WordPress Hooks + Helpful Tips
An aspiring WordPress developer must understand how to add JavaScript to the content management system (CMS). While the platform offers a graphical user interface, custom code lets you personalize your website further.
In WordPress, JavaScript lets you modify plugins or themes to expand your site functionality. You can also use the programming language to improve your web page appearance by creating dynamic and interactive content.
In this WordPress tutorial, we will explain how to add JavaScript using a plugin, hooks, and the enqueue function. Moreover, you will learn tips for adding code to the content management system.
How to Add JavaScript to WordPress
In this section, we will explain three methods to add JavaScript to WordPress. Since each method has a different difficulty level and use case, choose one based on your preferences.
Suggested Reading
Check out our what is JavaScript article if you are unfamiliar with the programming language.
How to Add JavaScript to WordPress Using the WPCode Plugin
WordPress plugins let you easily insert code to your site. They allow you to save and name code snippets, simplifying management if you have multiple custom scripts for different purposes.
A WordPress JavaScript plugin also stores your custom snippet, preserving the code after you change or update themes. One of the most popular options is WPCode.
Developers can also create a custom plugin to store their snippets. However, it is difficult and inconvenient since they must write the code from scratch.
Below are the steps on how to add custom WordPress JavaScript using WPCode. While it offers a paid plan, the free version is sufficient for this task.
- Download and install the WordPress plugin. Click the Code Snippet menu from your WordPress dashboard sidebar.
- Click Add Snippet. Since we are adding a custom script, hover over Add Your Custom Code (New Snippet) and click Use Snippet.
- Enter your custom snippet name. Select JavaScript Snippet from the Code Type drop-down menu.
- Write your code in the Code Preview field. For example, we will add a script that shows a welcome message window.
- Press the Activation toggle and click Save Snippet.
To insert the snippet, scroll down to the Insertion menu and choose a method. If you pick Auto Insert, the WordPress plugin will automatically load your JavaScript code to the chosen location.
Meanwhile, the Shortcode method lets you manually put the snippet anywhere using a block. To do so, copy the generated shortcode and edit the post where you want to add the JavaScript. Add a new Shortcode block and paste the code. Press Update to apply the changes.
Repeat the steps to add more JavaScript snippets. We recommend labeling them with a descriptive title to help you distinguish the codes easily.
How to Add JavaScript to WordPress Manually Using wp_head and wp_footer Hooks
To manually add custom JavaScript to WordPress, write the code in your theme’s functions.php file and use hooks to insert it into your website. We recommend creating a child theme to ensure the changes remain after an update.
Usually, you must download functions.php, edit it locally using a text editor, and re-upload it. At Hostinger, you can edit child theme files directly in your web browser using File Manager.
Otherwise, you can also include JavaScript in the header or footer using the Insert Headers and Footers plugin.
To add JavaScript to your WordPress site, use the wp_head and wp_footer hooks. You can also choose whether to apply the snippet sitewide or insert it on a specific page.
How to Use the wp_head Hook
The wp_head hook will insert JavaScript code into your site’s header section. By default, it will apply the snippet to all posts or pages in the entire site. Here’s an example code:
function javascript_function() { ?> <script> // insert your JavaScript code here </script> <?php } add_action ('wp_head', 'javascript_function');
Put your custom JavaScript code within the <script></script> tag and replace javascript_function with your desired function name.
How to Use the wp_footer Hook
Adding custom JavaScript code using wp_footer will insert the snippet into all footers throughout the entire WordPress site. The code structure is similar to wp_head, except we call another hook in the add_action callback function:
function javascript_function() { ?> <script> // insert your JavaScript code here </script> <?php } add_action ('wp_footer', 'javascript_function');
How to Add JavaScript to a Specific Page or Post
To add custom JavaScript code only to a single WordPress page, use the if conditional logic statement with the is_page function. Add the wp_header or wp_footer hooks to specify the location.
For example, we will insert the script into the footer of a WordPress page with 338 ID using the following code snippet:
function javascript_function() { if (is_page ('338')) { ?> <script> // insert your JavaScript code here </script> <?php } } add_action('wp_footer', 'javascript_function');
Alternatively, use the is_single function to insert the code to a specific WordPress post. The code is similar:
function javascript_function() { if (is_single ('338')) { ?> <script> // insert your JavaScript code here </script> <?php } } add_action('wp_footer', 'javascript_function');
Pro Tip
Alternatively, use Custom HTML or Code blocks to add code to a specific WordPress page.
How to Enqueue JavaScript to WordPress Using the wp_enqueue_script Function
If you have many scripts, adding JavaScript code snippets directly into the theme file may cause conflicts and performance issues.
To avoid them, write the snippet separately in another file and call it to the functions.php file using the wp_enqueue_script function. This method lets you determine when to load the script, where to insert it, and the dependencies.
The JavaScript files should be in the WordPress root folder, like the current theme path. We recommend creating a dedicated directory if you have multiple scripts to organize them easily.
For example, we will create a JavaScript file called welcome_box.js that shows a welcome message when visitors open the WordPress site. Here’s the code:
window.addEventListener('load', function() { alert('Welcome to the website'); })';
We save the file in the js folder inside the active WordPress theme directory. To apply the script, call welcome_box.js by adding the following wp_enqueue_script function in the functions.php file:
function enqueue_welcome_message_script() { wp_register_script('welcome-message', get_template_directory_uri() . '/js/welcome_box.js', array('jquery'), '1.0', true); wp_enqueue_script('welcome-message'); } add_action('wp_enqueue_scripts', 'enqueue_welcome_message_script');
The get_template_directory_uri() function gets the script file’s location. The array lists the dependencies for your JavaScript file, namely JQuery. If you don’t specify a post or page ID, the code will apply to the entire website by default.
Tips for Adding JavaScript to WordPress
In this section, we will explain tips for adding JavaScript to WordPress to ensure optimal website performance and development efficiency.
Ensure the Script Is Well-Written
Inserting the wrong JavaScript code into WordPress may cause issues that break your website’s appearance or functionality. In addition, it can lead to downtime, harming your business reputation.
To avoid such issues, adhere to the WordPress coding standard to ensure your JavaScript snippet is well-written. Also, always check your script in the development area before deploying it to the live site.
You can use XAMPP to set up a local WordPress site testing environment on your computer. At Hostinger, all our WordPress hosting plans provide a staging tool that lets you easily check changes safely before deploying them.
In addition, ensure your code editor has auto-completion and syntax highlighting features. These functionalities help minimize human errors like typos when writing scripts.
Suggested Reading
Check out our article to explore the best code editors with different features.
Use a JavaScript Minifier
If your website contains many long JavaScript snippets, the web browser will take longer to process and compile its code. This can slow down your web page performance, creating an unpleasant user experience.
To improve performance, remove unnecessary characters in your code like whitespaces, extra characters, or comments. While these elements are helpful during development, web browsers can process the code without them.
Various tools let you easily minify your JavaScript code. For example, you can use an online web-based application or install a free WordPress plugin like Fast Velocity Minify.
In addition to JavaScript, you can minify CSS and HTML files to improve your website performance further. Remember to create a backup before doing so since the shortened code may be difficult to read.
Use a Version Control
Aside from backup, use a version control system like global information tracker (Git) to help you track changes and restore your code when encountering errors. In addition, it improves development efficiency and collaboration.
Git allows multiple users to work on a project simultaneously without affecting each other’s code. Moreover, they can work on the file locally and push the changes to the live environment directly from their personal computer.
Hostinger WordPress hosting plans integrate with the Git version control system. Users can easily deploy a repository and enable automatic deployment by going to the Git menu in hPanel.
Conclusion
Adding JavaScript to WordPress lets you modify themes and plugins to expand your site’s functionality. There are three methods to do so: using a code snippets plugin like WPCode, the WordPress hook system, and the wp_enqueue_script function.
After installing and activating the plugin, navigate to the code snippet menu in your WordPress admin dashboard. Write your scripts and insert them automatically or using shortcodes. To add JavaScript manually, edit your child theme’s functions.php file.
The wp_header hook adds your code to the website’s heading, while wp_footer inserts it into the WordPress footer. To display the script on a single page or post, use the if statement with is_single or is_page functions.
Ensure your scripts are well-written to avoid errors that may harm your website functionality. In addition, minify the code to improve the page load speed and leverage a version control system like Git to improve development efficiency.
Suggested Readings
Learn More How to Use Code with WordPress
How to Add PHP Code to WordPress Post or Page
How to Add Custom CSS to WordPress
How to Add Schema Markup to WordPress
How to Edit HTML in WordPress
WordPress JavaScript FAQ
What Is JavaScript?
JavaScript is a lightweight scripting language for creating dynamic content in web development. It lets developers create animations, interactive elements, and dynamic backgrounds.
JavaScript works alongside other web development languages, such as HTML and CSS. Moreover, it is useful for server-side scripting and creating an API request.
Why Add JavaScript to WordPress?
Using JavaScript in WordPress lets users add additional content to their sites, integrate APIs, and modify plugins or themes’ behavior.
Moreover, JavaScript allows them to set up a third-party monitoring tool. For instance, users can add Google Analytics tracking code to record data like user interaction in their WordPress sites.
Does WordPress Use PHP or JavaScript?
A WordPress website mainly uses PHP for the core application and server-side functionality. Most plugins and themes also utilize the scripting language.
It supports custom JavaScript for client-side scripting, like providing interactive web content. WordPress users can also use the programming language to add dynamic functionality to themes or plugins.