If a Minified Stylesheet Exists, Use It!

Serving up minified stylesheets is one of the requirements Google has via its Pagespeed tests. A minified stylesheet is, at the most basic definition, simply a CSS file with all of the white space removed.

There are plugins out there which can do this kind of stuff for you, but I prefer to be a little more hands on and a little less reliant on other people’s plugins. So I always have the original style.css file in my theme, and then another, minified style.min.css version of the same file. This is the “right” way to do it because WordPress needs some information stored in the actual style.css file, which it uses to display certain things in your admin area.

Just having a style.min.css file won’t do you much good though, you’ve got to actually link to it. Which can be a pain, changing your code to point at the style.css file while you make changes and then back to the minified version.

Thus, I’ve created a simple little function to make it easy for you to switch back and forth between a style.css file and a style.min.css file. Just drop this into functions.php.

// if a style.min.css file exists, use that, otherwise use style.css
function style_or_min_style() {
$located = locate_template( 'style.min.css' );
if ($located != '' ) {
echo '<link rel="stylesheet" href="'.get_template_directory_uri().'/style.min.css" />';
} else {
echo '<link rel="stylesheet" href="'.get_template_directory_uri().'/style.css" />';
}
}

So now you can just quickly rename your style.min.css file (to anything, ie style1.min.css), edit the main CSS file, and then paste the minified CSS back into your style1.min.css file, rename it back to the original style.min.css, and you’re good to go.

CSS Minifier is a decent site for minimizing your CSS for you.

Up Next: How to Get the First Three Images Attached to a WordPress Post