Ayanize Ayanize - 4 months ago 11
CSS Question

Minify CSS in the output when added to the head in WordPress

I am adding CSS in the from a textarea. Is there a way I can easily minify the output when added in the

<head>


CSS

#logo img{
opacity: 0.8;
}
#header{
background-color: red;
}

function add_css_to_head(){
$opt = get_option( 'get_css_head' );

echo '<style type="text/css" id="get_css_head">' . "\n" . stripslashes( $opt ) . "\n" . '</style>';
}
add_action('wp_head', 'add_css_to_head');


I want the output like this in the
<head>


#logo img{opacity:.8}#header{background-color:red}


Thanks in advance

Answer

You can use a combination of php heredocs and php str_replace... Like this

function add_css_to_head(){
$buffer = <<<EOD
#logo img{
    opacity: 0.8;
}
#header{
    background-color: red;
}
EOD;

$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
$buffer = str_replace(': ', ':', $buffer);
$buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer);
echo($buffer);

}
add_action('wp_head', 'add_css_to_head');

EDIT

If you're getting output from theme options, then the code would look like this

function add_css_to_head(){
$buffer =  get_option( 'get_css_head' );

$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
$buffer = str_replace(': ', ':', $buffer);
$buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer);
echo($buffer);

}
add_action('wp_head', 'add_css_to_head');
Comments