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.
Published on Nov. 8, 2010 at 3 p.m. by Nicolas and tagged minify, wp_register_style, WordPress, CSS, WordPress theme, theme, SEO, development, wp_enqueue_style. You can follow the discussion with the comment feed for this post.

1 comment

  • avatar
    Vernon Fowler wrote this comment on Feb. 19, 2012, 9:08 a.m.
    Now that is neat. Still relevant too I believe. Will try this out soon.
    Reply to this comment

Start a new thread

Cancel reply
Markdown. Syntax highlighting with <code lang="php"><?php echo "Hello, world!"; ?></code> etc.