How To Add JavaScript to WordPress

  • 3 min read
  • by

Introduction

Sometimes the ordinary functionality of our WordPress site needs to be enhanced. We can ordinarily do this with PHP snippets. But did you know, you can do this with JavaScript as well? That’s correct. We can leverage JavaScript and use it on your WordPress site. The process is really similar to the process of enhancing the current theme, but if you don’t know how to do that, there’s no need to worry. In this tutorial, we’ll walk you through.

Adding the JavaScript Code

Adding JavaScript by modifying the theme’s source code

The first way you can add JavaScript code on your WordPress site is to modify the source code of your current theme. JavaScript can be declared anywhere, but usually is placed on the header or footer of a web page. We recommend going with placing the JavaScript declaration in the header, since it will load the scripts first before the rest of the page is rendered.

Since WordPress themes are usually composed of several files, the declaration should be made in the headers.php file (or wherever the head tags of the page can be found). To edit the file, we can do so through the WordPress admin dashboard, by going to the Edit Themes page. To access the page, hover over Appearance then click on Theme Editor.

WordPress Dashboard

Once in the Edit Themes page look for the header.php file as seen below.

search for the header.php file

When the file loads, declare your script within the head tags.

declare your script

Adding JavaScript Code using the Insert Headers and Footers Plugin

We can also add JavaScript code by using a plugin. One plugin that can do this is through the Insert Headers and Footers plugin. This plugin allows us to add code snippets in either the header and footer of every WordPress page. The plugin can be found in the Add Plugins page of the admin dashboard.

search for the Insert Headers and Footers Plugin

When the plugin is installed and activated, we can immediately add the piece of JavaScript code that we need to use. This can be done through the plugin’s page as seen below. Just add, the snippet you need then click on Save.

add the piece of JavaScript code

That’s all you need to do, and the script should be loaded on any post on your WordPress website.

Conclusion

Now you know how to add JavaScript on your WordPress sites. Now you can do it on your own.

Thank you for reading our tutorial, we hope you learned a lot!

nv-author-image

Kristin Eitel

Leave a Reply

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