Skip to main content
WordPress made easy with the drag & drop Total WordPress Theme!Learn More

Adding Javascript To WordPress Themes The Right Way

February 13, 2018

There is a specific way for adding Javascript to your WordPress theme in order to prevent any conflicts with plugins or parent WordPress Themes. The problem is that many “developers” call their javascript files directly in the header.php or footer.php file which is the incorrect way of doing it.

In this guide I will show you how to correctly call your javascript files using your functions.php file so they load right into your site’s head or footer tag. This way if you are developing a theme for distribution and your end user wants to modify the scripts via a child theme they can or if they are using minifying/caching or other optimization plugins they will work correctly. And if you are working with a child theme you  your scripts are added the right way, without copying the header.php or footer.php files into your child theme which are shouldn’t ever be necessary (when working with a well coded theme)

Wrong Way To Add Javascript To WordPress Themes

Calling the javascript in your header.php file or footer.php file such as shown below, is NOT the correct way and I highly recommend against it, often times it causes conflicts with other plugins and doing things manually when working with a CMS is never a good idea.

<script src="https://site.com/wp-content/themes/mytheme/js/my-script.js"></script>

The Right Way To Add Javascript To WordPress Themes

The better for adding javascript to your WordPress theme is to do so via the functions.php file using wp_enqueue_script. Using the wp_enqueue_scripts action to load your javascript will help keep your theme out of trouble.

Example

wp_enqueue_script( 'my-script', get_template_directory_uri() . '/js/my-script.js', array(), true );

The code above will load the my-script.js file on your site. As you can see I have only included the $handle but you can also add dependencies for your script, version number and whether to load it in the header or footer (default is header).

The wp_enqueue_script() function can technically be used in any theme or plugin template file but if you are loading global scripts you’ll want to place it either in your theme’s function.php file or in a separate file specifically intended to load scripts on the site. But if you are only looking to load a script on a specific template file (for example on gallery posts) you could place the function right in the template file, however, personally I recommend keeping all the scripts in one place and using conditionals to load scripts as needed.

WordPress Hosted Scripts

One cool thing about WordPress is there are already a bunch of scripts hosted by and registered that you can use in your theme development. For example jQuery which is used in almost every project should ALWAYS be loaded from WordPress and never hosted on a 3rd party site such as the Google. So before you add a custom script to your project check the list of registered scripts to make sure it’s not already include in WordPress and if it is you should load that one as opposed to registering your own.

Using The WordPress Enqueue Hook

Previously we mentioned the function needed to load a script on your site, however, when working with non template files such as your functions.php file you should be adding this function inside another function hooked into the proper WordPress hooks, this way your scripts get registered with all the other scripts registered by WordPress, 3rd party plugins and your parent theme when using a child theme.

WordPress has two different action hooks you can use for calling your scripts.

  1. wp_enqueue_scripts – action used to load scripts on the front-end
  2. admin_enqueue_scripts – action used to load scripts in the WP admin

Here is an example (that would be added to your functions.php file) of how to create a function and then use the WordPress hook to call your scripts.

/**
 * Enqueue a script
 */
function myprefix_enqueue_scripts() {
    wp_enqueue_script( 'my-script', get_template_directory_uri() . '/js/my-script.js', array(), true );
}
add_action( 'wp_enqueue_scripts', 'myprefix_enqueue_scripts' );

Note: See how we are using the “get_template_directory_uri” function when defining the location of your script? This function creates a URL to your theme folder. If you are working with a child theme you will want to use “get_stylesheet_directory_uri” instead so that it points to your child theme and not the parent theme.

Adding Inline Javascript Code

While you can easily paste inline javascript in any template file via the script tag it can be a good idea to also use WordPress hooks for adding your inline code, especially when it’s a core plugin or theme code. Below is an example of adding inline scripts to your site:

function myprefix_add_inline_script() {
    wp_add_inline_script( 'my-script', 'alert("hello world");', 'after' );
}
add_action( 'wp_enqueue_scripts', 'myprefix_add_inline_script' );

What this will do is add your inline javascript after the previously registered “my-script” script. When using wp_add_inline_script you can only add inline code either before or after an already registered script so if you are trying to modify the code of a particular script make sure it’s loaded after it, or if you just need to add some custom code you can hook it to the jquery script which is generally loaded by most WordPress themes and if not you can use the wp_enqueue_script to load the WordPress hosted version of jQuery.

By using this method people can easily remove your inline scripts via a child theme or plugin add-on, it keeps all your custom javascript neatly organized and it is parsed by WordPress which can be safer. And if you are using a child theme you can load your scripts via your functions.php file instead of copying over the header.php or footer.php files over to your child theme.

That said, if you are working in a child theme you don’t need to do this you can simply dump your code into your header either using the wp_head or the wp_footer hooks such as the example below:

add_action( 'wp_footer', function() { ?>
	<script>
		( function( $ ) {
			'use strict';
			$( document ).on( 'ready', function() {
				// Your custom code here
			} );
		} ( jQuery ) );
	</script>
<?php } );
javascript-wordpress
Article by AJ Clarke WPExplorer Staff
Published on: April 14, 2011
Last updated on: February 13, 2018
Subscribe to the Newsletter

Get our latest news, tutorials, guides, tips & deals delivered to your inbox.

8 Comments

  1. stephane says:

    Where do you put the add_action ? in the function.php ?

    • AJ Clarke | WPExplorer says:

      In functions.php is fine. But also now in WordPress you can enqueue a script on any file without having too hook into wp_enqueue_scripts

  2. stephane says:

    Thanks 🙂

  3. Alan says:

    Do you have to add this code for every file? Is there a way to add multiple files without having to call a function for each one?

    • AJ Clarke | WPExplorer says:

      You have to use wp_enqueue_script() for each file you want to load, but you can place them all into 1 function and hook into “wp_enqueue_scripts”. If you really want I guess you could create an array of the file names you want to load and if they are all in the same location do a foreach loop to go through each of the items in the array so you only use wp_enqueue_script() once.

  4. Dan says:

    Hi AJ,

    For all of us noobs out there, can you detail (and visually illustrate) where “The Action” and the “Example” (both) would be placed? Maybe even break it down to show how the functions file would look after you have added the script?

    Cheers,
    Dan

    • AJ Clarke says:

      Hi Dan,

      I just updated the post a bit, but have a look at the CODEX it explains it much better. You can use the wp_enqueue_script function technically anywhere, however, it’s much cleaner to keep it in your functions.php file or a file that is called from the functions.php, because having all the scripts loaded from 1 place makes it easier to troubleshoot, debug and update.

  5. Ana says:

    Awesome article!!! Thanks a lot

Leave a Reply

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

Learn how your comment data is processed by viewing our privacy policy here.