One of the most important things about WordPress is also one of the more initially confusing parts: how exactly do I add my own JavaScript files and CSS sheets in “the WordPress way”? The WordPress way of adding stylesheets and script files has a number of advantages, but it’s also a bit complicated and confusing at first glance. And that’s the reason we’ll cover it today.
What You Shouldn’t Do & Why You Shouldn’t
If you’ve ever made either a small JavaScript file or a stylesheet, you probably know how to add to a page in the HTML way. It typically looks something like this:
<link rel="stylesheet" media="screen" href="http://wpshout.com/wp-content/themes/wpshout-pu/style.css" />
<script type="text/javascript' src='http://wpshout.com/wp-content/themes/wpshout-pu/script.js"></script>
If you’re distributing a plugin or theme, you’re not making it all that possible — let alone easy — for someone else to change the way that your JavaScript or CSS loads.
These may be in the header of your document. In the case of the <script>
tag, it can really be just about anywhere on your page. For non-WordPress work, these are typically more than good enough to get your styles and scripts available with your HTML, and you’re all set with a simple thing like that. But if you remember, I said this isn’t how you should do it with WordPress. Why? Great question.
First and foremost, if you’re not making a theme, you actually don’t really have the ability to easily touch raw HTML that will certainly be shown on a page at all. It just isn’t something that’s native to a WordPress plugin. And when you’re needing to add scripts and styles, plugins are really the primary use case for most people.
More important, if you’re distributing a plugin or theme, you’re not making it all that possible — let alone easy — for someone else to change the way that your JavaScript or CSS loads. Maybe they want to load theirs before yours, or after, or maybe they want to stop yours from showing up for a specific styling or functionality reason. All of these are reasons that WordPress has a pretty robust system for adding scripts and styles that doesn’t involve the basic HTML-writing that we demonstrated above.
The Right Way To Load a Stylesheet or Script File In WordPress
So how do we do it so that other plugins or themes can take control over our scripts and styles if need be? We add them to the page the WordPress way: with wp_enqueue_script()
and wp_enqueue_style()
. Yep, those are PHP functions, rather than just markup, and that does mean you’ll have to do a little more with PHP. But trust me, if this is your first PHP it’s a good and simple problem to start with.
WordPress automatically takes queued-up scripts and styles and gets them on the page, manages the position of things in the queue, and listens if a new entrant in the queue has a special priority request.
As you may have been able to guess from their similarity in naming, both of these functions do quite a similar thing. Before we dive into the PHP, here’s a quick summary of what each function does. Essentially, in a typical HTML page you’ll have a block of stylesheets registered and listed, and then the same for your JavaScripts. This is essentially the “queues” that these functions are talking about. They’re that big block of .css
or .js
files that should come out on a WordPress page.
WordPress automatically takes care of the process of taking all those queued up scripts and styles and gets them on the page. And it also manages the position of things in the queue, and listens if a new entrant in the queue has a special priority request. (And finally, though we won’t do it here, because there’s a queue, this also provides an ability for other actors to make changes to the queue before the scripts go out to the page. If we were adding our files with pure HTML, that wouldn’t be possible at all.)
So a very simple example of how you’d load a new CSS and JS file for a plugin looks something like this (in your WordPress theme’s functions.php
):
function wpshout_script_and_style_includer() {
wp_enqueue_script( 'our-js', plugins_url( '/path/to/file.js' , __FILE__ ) );
wp_enqueue_style( 'our-css', plugins_url( '/path/to/file.css' , __FILE__ ) );
}
add_action( 'wp_enqueue_scripts', 'wpshout_script_and_style_includer' );
We’ll mostly leave aside the add_action()
which is what is actually invoking our function. If you’re not already familiar with how actions work in WordPress, or could just use a refresher, you should check out an old article of mine on the topic. The executive summary is as follows: when WordPress hits the place in the page-creation flow where it wants to know about all the scripts and styles it should have — that’s the wp_enqueue_scripts
“benchmark” — our function will get invited to the “naming of scripts” party and get to contribute the CSS and JS files that we want to have put on the page.
Both of these function have a similar method signature for their first parameters. The first thing you specify is the “handle”, or short name by which this script is called. This seems kind of superfluous at first, but if you’re ever troubleshooting dependency issues or something, it’s pretty valuable that WordPress has these around.
The second argument is just the absolute URL of the script in question. In the case of my snippet, our scripts are in our plugin’s directory structure, so we declared them using the WordPress plugins_url()
helper function. If you have the file hosted in the theme, or hosted elsewhere on internet, you’d just change that parameter to give the working full URL. And if we’ve done everything right, those four lines will be enough to make that happen for us. Pretty simple really.
Some of the Finer Points of wp_enqueue_*
There’s much more we can cover on the topic of including scripts and styles. You’ll see a variety of methods, means, and variations if you spend much time around WordPress themes and plugins. In this section, I’ll try to quickly summarize some of the more interesting facets of what I’ve learned.
Declaring Dependencies
If your JavaScript relies on jQuery — so common it’s the example we’ll go with — you’ll help yourself a lot if (1) you let WordPress take care of getting jQuery in place for you, and (2) you do this by telling WordPress you need jQuery. (Don’t forget that you’ve got to be a bit more careful with your $s when using WordPress’s jQuery.) It’s a pretty painless process, though I sometimes find myself needing to look at Codex to confirm the syntax:
wp_enqueue_script( 'our-js', 'path/to/file.js', array('jquery') );
That third parameter, the array with the word 'jquery'
in it, tells WordPress that our JavaScript needs jQuery loaded, and that we want to only show up after jQuery is there. WordPress will take care of the ordering for you if you’ve got all your dependencies declared. (jQuery is one of a number dependencies WordPress makes available for you to use without any setup. You can find the whole list best on the Codex.)
While dependency and ordering issues are less common in my experience with CSS, you still see them sometimes. And there too WordPress has provided for you. It’s exactly the same syntax and exactly the same dynamics. You make an array of your dependencies — the things you need to exist before you appear — with their short-name and WordPress takes care of the rest. Used well, this lets you avoid some of the more painful specificity olympics—or, worse, !important
contests—you’d otherwise play.
Registration Before Enqueuing
The primary reason that people do this is that it makes your dependencies easy: you don’t have to worry about your ordering and WordPress will auto-enqueue previously
register
ed necessary scripts you declare as dependencies.
One thing that’s common, and sometimes recommended, is that before you call your wp_enqueue_style
(or _script
), you actually make a call to wp_register_style
(or _script
). The primary reason that people do this is that it makes your dependencies easy: you don’t have to worry about your ordering and WordPress will auto-enqueue previously register
ed necessary scripts you declare as dependencies. It also has the advantage that once registered, a script can be enqueued separately (somewhere totally disconnected in your code) with a simple reference to that short handle you used when you registered.
Admin-Only Scripts and Styles
Another thing you may want to do is make it so that your scripts or styles are included only in the admin area. You don’t use different functions than what we’ve been talking about, you simply use a different action hook. In this case, you’d want to use the admin_enqueue_scripts
hook, rather than the more universal wp_enqueue_scripts
we were using in the example.
Force JavaScript into the Footer of Your Page
It’s commonly recommended that you delay JavaScript loading as much as possible to improve initial page load speed. WordPress doesn’t yet have native support for deferring your scripts so that they’re explicitly known by browser as meant to load asynchronously (though there are ways…), but you can easily tell WordPress that you want to load a JavaScript file in the footer, rather than in the header. You do this with the fifth parameter of your wp_enqueue_script()
function. Like so:
wp_enqueue_script( 'our-js', 'path/to/file.js', array('jquery'), false, true );
What We’ve Learn About Scripts and Styles in WordPress
There’s a lot more to this topic. You can spend a lot of time playing and changing specific ways in which yours or other plugins get to load their stylesheets and JavaScript files. We’ve done a lot more than scratch the surface, but the finest of fine points of this topic are left as an exercise to the reader. Hopefully you’ve learned more than a thing or two, and happy hacking!