How to Enqueue a CSS Stylesheet in WordPress How to Enqueue a CSS Stylesheet in WordPress

How to Enqueue a CSS Stylesheet in WordPress

The right way to add your styles without breaking your site.

If you’re anything like me – you love to throw together various CSS snippets and use them to customize your WordPress site’s design. But, despite all the fun, those snippets can quickly add up to 1,000+ lines of CSS – which gets loaded on every single page, even if that custom CSS isn’t needed for that particular page; a big no-no for performance.

I know for a fact that WP Rocket’s caching plugin has a feature that removes unused CSS, but it’s still in beta and might break things. Besides, by enqueuing the stylesheet – you can still reap the benefits of both minifying the file but also caching it.

So, the first thing you want to do is move all your custom CSS to a new stylesheet, in my case – I created a file called cstm-design.css and saved it in my root directory. You can change the directory to whatever you like, including /wp-content/ or your theme’s directory.

As a side note, I did not move all my CSS to this file. Some classes I still want to style on a frequent basis, and having to edit the .css file and then reload the cache is too time-consuming of a process. So, only put the CSS inside your stylesheet file that you know you won’t need to edit on a frequent basis.

The next thing you want to do is open up your functions.php file – either from the Theme Editor panel or by doing it from the command line if you host your site on a VPS.

Then copy & paste this snippet:

add_action('init', 'my_custom_css_stylesheet');
 
function my_custom_css_stylesheet() {
    wp_register_style( 'custom-design', '/cstm-design.css' );
}
wp_enqueue_style( 'custom-design' );

That’s it.

You can change the file location by renaming the /cstm-design.css part.

For example, if your custom stylesheet is inside /wp-content/ – you would need to change it to /wp-content/cstm-design.css.

It goes without saying this is a pretty quick and dirty technique.

If you read the official reference, it’s possible to use wp_enqueue_style() to add version numbers, call child themes, and also specify media types. In our method, we simply call it as is, and most caching plugins will rotate the version automatically.