And if you’ve read about all of this before, feel free to skip to the code roundup at the end of the article.
Many people new to WordPress development, but familiar with including scripts generally in web development, often want to just copy header.php to their child theme directory and start including scripts directly within the
<head>. — Don’t do this. Keep reading!
Now, I’ll outline specifically how to do everything discussed in the last section.
So, if you’d like to utilize jQuery, here’s an example of how to set up within your script.js file, when DOM is ready.
Hook a Function for Your Scripts
Next, we need to set up a function and hook it to
wp_enqueue_scripts, which is where WordPress processes included scripts and stylesheets. You’ll do this from your child theme’s functions.php.
Enqueue Your Scripts
And then we need to actually enqueue our scripts. So, within the
my_scripts() function you just created, we need to call
wp_enqueue_script() for each script we’re including.
wp_enqueue_script( 'foo', esc_url( get_stylesheet_directory_uri() . '/assets/js/foo.js' ) );
In the above line, you can see we’ve passed in the following two parameters to
- A unique handle for the script.
And if any of our scripts, require other scripts outside of what we’re doing to load before it, we can pass an array of their handles, for the third parameter. For example, if our “foo” script required that jQuery be loaded, we’d modify it like the following.
wp_enqueue_script( 'foo', esc_url( get_stylesheet_directory_uri() . '/assets/js/foo.js' ), array('jquery') );
wp_enqueue_style(). This might seem strange, but it was announced awhile back that separate hooks for enqueueing CSS files have been deprecated. It’s now considered best practice to enqueue all stylesheets and scripts in a single function, hooked to
wp_enqueue_scripts. Learn More
So here’s a roundup of everything we’ve discussed through the article, putting it all together.
First, you’ll organize all your scripts in a directory of your child theme like /assets/js/, including your custom script.js file.
/assets/js/foo.js /assets/js/bar.js /assets/js/script.js
And if you’re utilizing jQuery from within your custom script.js file, it might be set up something like the following.
And in order to include those scripts, your child theme’s functions.php should have something like the following.