WordPress: adding a CSS minifier to our theme

Adding a CSS minifier to our WordPress site is quite a simple task. All we need is a single PHP script to be added to our theme that accepts as its sole GET parameter the URL of our main CSS file. Then we can use this script in our header.php template. Let's see how.

Creating minify.php

We can create the PHP script and save it in a subdirectory of our theme (e.g. /theme/inc/css/minify.css):

<?php
header( "Content-type: text/css" );

$file = isset( $_GET[ 'css' ] ) ? $_GET[ 'css' ] : '';
if( !$file || array_pop( explode( '.', $file ) ) != 'css') {
	die( 'Invalid Parameters' );
}

$content = @file_get_contents( $file );
echo minify( $content );

function minify( $css ) {
	$css = preg_replace( '#\s+#', ' ', $css );
	$css = preg_replace( '#/\*.*?\*/#s', '', $css );
	$css = str_replace( '; ', ';', $css );
	$css = str_replace( ': ', ':', $css );
	$css = str_replace( ' {', '{', $css );
	$css = str_replace( '{ ', '{', $css );
	$css = str_replace( ', ', ',', $css );
	$css = str_replace( '} ', '}', $css );
	$css = str_replace( ';}', '}', $css );

	return trim( $css );
}
?>

Adding the minifier to the theme

We can use our script as follows:

<link rel="stylesheet" type="text/css" media="all" href="<?php echo get_bloginfo('template_url') . '/inc/css/minify.php?css=' . get_bloginfo( 'stylesheet_url' ); ?>" />

Simply add the above code in the head section of your header.php template file.

Back to top