How to minify WordPress theme stylesheets properly
If you build WordPress theme you'll eventually come to the point where you want to minify the stylesheets. But the WordPress theming system has a fundamental flaw: It expects theme headers like name, version information etc. to be in the style.css
.
This is bad because removing the headers from the css file more or less breaks the theme in the eyes of WordPress. Not to mention that you waste bandwidth and have to expose the theme information to the world.
You could use a plugin of course that minifies the CSS on the fly, but why waste memory and CPU cycles for something that can be done once with a script?
So how do you get around this? The solution is rather simple. Use the default style.css
file only for the theme headers, and don't make the browsers load it. Use a different file for your real CSS. Here's a snippet for your functions.php
that accomplishes this.
<?php if ( !is_admin() ) { wp_register_style( 'my-style', get_bloginfo( 'stylesheet_directory' ) . '/css/site.css', false, 0.1 ); wp_enqueue_style( 'my-style' ); }?>
The site.css file in this example could be created by minifying a site-src.css file. I use a trivial PHP script to do such things, but I won't add it here because I have no idea where I got it from or who the author is.
Anyway, there are many minify scripts available for download.
8 comments
Reply