Add Javascript to WordPress

WordPress is so extensible that it allows you to easily add new features and functionalities to your website without actually having to redesign your entire theme. Rather you can add the functionality by simply adding plugins. And if the functionality you would like to add is too small to create a plugin (which comprises just a few lines of code), you can use the functions.php file rather than creating a separate plugin.

(Special note: Are you looking for a list of tweaks/tricks you can easily make on your WordPress site without using a plugin? You may refer our guide here:101 WordPress tricks every serious blogger must know.)

The best thing about the functions.php file is that it acts like a plugin, which can be used to add features and extend the functionality of both the theme as well as WordPress installation.

That said, often times while enhancing your website with new features you’ll require adding additional javascript files to your WordPress theme especially if you’re looking to provide a friendlier user experience to your website visitors or if you’re verifying your site with third-party services.

Though you can easily add Javascript code directly to your header.php file, the problem with this method is that it can even cause conflicts with other plugins when they load their own JS scripts.

In this article by CollectiveRay, we take a look at the right way to add javascript to WordPress themes. As WordPress developers, this is one of the things which we will have to do very often.

If you're not confident of tweaking the code yourself, you might want to look at this article to learn how to recruit the best WordPress developer for your business: https://www.collectiveray.com/wordpress/wordpress-tips-and-tricks/wordpress-developers-for-hire.html

 

JavaScript in Your Template 

To use JavaScript repeatedly within your site, maybe you have created a script or need to add a 3rd party script in all your pages, you can  set the call for the JavaScript, or the script itself, in the head of your header.php template file. This should be added between the meta tags and the style sheet link. This is exactly the same as if you were adding JavaScript in any HTML page.

 

To "add" the JavaScript file into your site, in the head, you can use the following code:

 

<script type="text/javascript" src="https://cdn.collectiveray.com/scripts/myscript.js"></script>

Make sure that you have defined the type correctly, otherwise your site will not be valid.

You can then add any reference to functions used within the file you just added to the HTML where you need to use it. 

For example, this is an example of using the function you just added.

<h3 class="heading3">
<a href="/<?php the_permalink() ?>" >
Heading goes here</a></h3>
<div>
<script type="text/javascript">
<!--
myscript();
//--></script>
</div>

 

 

Adding Javascript to WordPress: The right way

The recommended method to add a javascript file to your WordPress theme is by using functions.php file with wp_enqueue_script.

Here’s how to do it.

Just open your functions.php file and copy the below code snippet to it. Make sure you replace the template URL with yours before saving.

function my_theme_scripts_function() {

  wp_enqueue_script( 'myscript', get_template_directory_uri() . '/js/myscript.js');

}

add_action('wp_enqueue_scripts','my_theme_scripts_function');

If you’re using a child theme, you’ll need to use get_stylesheet_directory_uri() instead of get_template_directory_uri()

Adding Javascript to WordPress using plugins

If you would like to simply use a plugin for uploading a javascript to the theme’s header or footer file, ‘Insert Headers and Footers’ plugin could be the right choice for you. As the name says it allows you to add scripts to the header and footer files by hooking into wp_head and wp_footer.

You can download Insert Headers and Footers here.

Headers and Footers Plugins

This plugin is perfect because it allows you to add any script without running any risk of breaking stuff, you don't have to change any code yourself. (Of course, you need to make sure that the actual script is valid). 

Instead of modfiying theme files with the custom Javascript, the plugin allows you to insert the code in either the header or the footer of your site.

 

After you need to download and install the plugin:

  • Log in to your site's backend or admin.
  • Go to Plugins > Add new
  • Search for "Header and Footer" plugin and click on Install Now.
  • Once it has installed, click on Activate
Headers and footers

Upload a custom Javascript file

  • First you need to prepare the file for inclusion
  • Save your JavaScript code or file into a new test file with the .js extension.
  • Upload it into your site to the following folder: wp-content/themes/<theme-you-are-using>/js/
  • Go to Settings > Insert Headers and Footers.

We now have a couple of choice to load our file:

  1. Scripts in header (load inside head tag)
  2. Scripts in footer (load before closing </body> tag)

Use the location that matches best your specific needs using the following as an example:

<script src="http://www.website.com/wp-content/themes/<theme-you-are-using>/js/file.js"></script>
 
Insert script in head
  • Click on the "Save" button to finish and save.

Load custom JavaScript without a file

The 2nd option you can use us to the code directly into WordPress without the need of using a specific file. This can be used when you are using a 3rd party service, such as Google Analytics, Drip, or other tool which needs some script added to your site.

add script / code directly
  • Once again, click "Save" to finish.

 

Reload the front-end, and check your website's source to make sure that the code is now showing.

It's also a good idea to browse a few pages to confirm that everything still looks like it is working ok.

 

Download the list of 101 WordPress tricks every blogger should know

101 WordPress tricks

Click here to Download Now

Featured On

Inc Magazine Logo  

Sitepoint logo  

CSS Tricks logo   

webdesignerdepot logo   WPMU DEV logo   

and many more!

Where are we hosted?

This site is proudly powered by FAST VPS InMotion Servers and given an insane speed thanks to MaxCDN!

Web Hosting MaxCDN - Speed up your website

New! DIVI 3.1 WordPress Template + PageBuilder

You'll surely create a perfect website with Divi 3.1!

Get an exclusive 10% OFF for CollectiveRay visitors until

Divi 3

 

Monstroid2 (Updated!)

The best-selling template from TemplateMonster has been given an awesome upgrade!

We've got an exclusive 10% OFF for CollectiveRay visitors on Monstroid2 until - use Coupon Code: collectiveray

Monstroid2 Super Update

 

TemplateMonster Bundles

Awesome bundles for awesome websites. $1300 worth of products for $49 only!

We've got an exclusive 10% OFF for CollectiveRay visitors until - use Coupon Code: collectiveray

TemplateMonster Bundles

 

The Outstanding HungryJPEG Bundles

AWESOMENESS! Bundles of premium font + graphic packs at more than 96% OFF!  Get a bundle for just $9 - ONLY!

The Hungry JPEG Awesome font bundles

 

Advertise on CollectiveRay.com

CollectiveRay (formerly known as DART Creations) is interested in developing partnerships with mutual benefit. If you like the stuff we publish and would like to develop a relationship, we'd be happy to hear from you. Go on - drop us a line - we'd love to hear from you :-)

 

 

Disclosure: CollectiveRay is funded personally out of pure passion for helping people working with websites. We do however generate some income through recommendations of products. This means if you click on a link and purchase an item we link to, we will receive a small sum out of that sale. We usually partner with vendors to make your purchase cheaper than buying direct.

who are we?

CollectiveRay is run by David Attard - working in and around the web design niche for more than 12 years, we provide actionable tips for people who work with and on websites. We also run DronesBuy.net - a website for drone hobbyists.

David attard

Follow us on Social

Follow us on Facebook   Follow us on Google+   Subscribe to our RSS Feed   Follow us on Twitter