How to Conditionally Enqueue a JavaScript File in WordPress

Enqueuing is the WordPress way to add a stylesheet or JavaScript file on a page. We already published a Quick Guide about including your JavaScript in WordPress. This time, though, we’re adding an extra wrinkle: how do you only enqueue a JavaScript file on certain pages of your WordPress site. That’s the focus of this here Quick Guide.
There are lots of reasons you may want to conditionally enqueue a file. Some examples:
- You want a JavaScript pop-up to only appear on your homepage (or on all pages BUT your homepage)
- You only want a JS file or CSS ruleset on a certain page
- You only want to load a script or style for certain pages
All of these can be done with WordPress conditional tags. Here’s the video explaining how to do this:
How to Only Load a JavaScript File on Certain Pages in WordPress
- If you’ve not already made written the action hook, start there. You can follow this Quick Guide for the sake of doing this.
- We’re going to need to a
if
with a conditional tag. If you don’t know what conditional tag to use, check out the exhaustive Codex page of them. Some common and useful conditional tags:is_single()
tells you if you’re on a single-post or single-page view. Great of scripts that should only be on articles. Bonus: include a slug and it’ll only be shown on that specific one, likeis_single('page-slug')
.is_archive()
tells your if the current page is displaying a set of archives, whether for an author, a tag, a date range, a category, etc.is_home()
is for when the front blog page is being display.
- Wrap your
wp_enqueue_script
orwp_enqueue_style
call in anif () {}
block. The conditional tag (or tags) you’re going to use goes in the parenthesis. Thewp_enqueue_script
goes in the curly braces ({}
). - You’re all set!
The power and simplicity of conditional tags is really great. I love how they read a lot like English! Hopefully this gets you a solid start.
Our Code for Conditionally Enqueuing a Script File
add_action('wp_enqueue_scripts', 'qg_enqueue');
function qg_enqueue() {
if (is_home()) {
wp_enqueue_script(
'qgjs',
plugin_dir_url(__FILE__).'quick-guide.js'
);
}
}
Further Reading on WPShout about Conditional Tags and Enqueuing Stylesheets or Scripts
https://wpshout.com/wordpresss-conditional-tags/
https://wpshout.com/everything-custom-scripts-styles-wordpress/
How to Include JavaScript Files on Your WordPress Site with wp_enqueue_script()
Add a Comment