Doing things the WordPressy Way
Yes, technically it’s possible to just drop scripts into template files, but it’s not the correct method to use on WordPress sites. WordPress is pretty particular on how it handles JS.
Register Scripts via functions.php
Just a heads up, the functions.php
file is pretty sensitive. WordPress requires everything in functions.php
to have absolutely perfect syntax, otherwise it will break your entire site. Please don’t mess with it if you’re on live install or don’t have a way to access this file should you get the dreaded white screen of death.
Once you agree to the above mentioned terms and conditions, you’ll want to register your new Javascript file with the wp_enqueue_scripts
function, which is most commonly used with a hook like so:
<?php
// enqueue script tabs
function add_scripts() {
wp_enqueue_script( 'coolScript', get_stylesheet_directory_uri() . '/js/coolScript.js', array(), '1.0.0', false);
}
add_action( 'wp_enqueue_scripts', 'add_scripts');
There’s definitely a lot going on here, but basically wp_enqueue_script
is expecting a lot of arguments, some required, some optional. The first argument is the name of the script, and that’s required. Next is the filepath of the named script, which funny enough, is actually optional. The default filepath is just an empty string, which refers to the root of the WordPress installation.
In the above example, I actually used another WordPress function get_stylesheet_directory_uri();
which just returns the directory of the currently activated child theme, then you can just concatenate the rest of the filepath with a period in PHP.
Next is an array of dependencies, so if your script depends on other scripts, you can pass those into this array. Mine didn’t have any dependencies, so I just left it as an empty array.
Next is the version number, which is given as a string in single quotes. And finally, the last argument is a boolean which is $in_footer
. This is set to false
by default. WordPress loads all scripts at the very top of the page, up in the <header>
. If your Javascript is manipulating or selecting an element later on down the page, there’s a good chance your script won’t work in the <header>
.
If that’s the case, and you need to load your JS in the footer in order for it to work, you can set the very last argument to true
and that will drop your script all the way down to the bottom, just before the closing </body>
tag.