WordPress Stylesheets: wp_enqueue_style

WordPress Stylesheets: wp_enqueue_style

If you're building a WordPress plugin, or simply dealing with including WordPress stylesheets in your theme, there are a few approaches you can take. For the most part, I've included stylesheets for WordPress sites in header.php, since (obviously), header.php is included in every other site file. It seems this is relatively standard practice for WordPress sites. I see it all the time:

However, as it turns out, there's a better way of doing this - using wp_enqueue_style.

Why not just include them in header.php? It seems pretty simple to do that and never think twice. Well, first, using wp_enqueue_style ensures that your stylesheets will load in the correct order. Second, it comes in handy if you're trying to restrict scripts and/or css from loading on certain page (for scripts you'd want to use wp_enqueue_script), or alternatively, if you want to load specific stylesheets only on plugin pages.

You can execute this in a number of places, including functions.php, or, if you're building a plugin, from within your main plugin file. There are a few parameters for wp_enqueue_style including $handle (the name of the stylesheet), $src (the path to the stylesheet), $deps, $version, and $media.

I really wanted to include a bit about template_redirect in this post, as it is related, but "a bit" turned into three paragraphs, so stay tuned!