3

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

2 Answers 2

2

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');
2
  • It perfectly works man. Let me test this a bit comprehensively and I will updated. This will be accepted answer. Let me check once again.
    – Ayanize
    Commented Aug 2, 2016 at 13:49
  • Yes yes. I got it like this. Thanks once again. It's working lovely.
    – Ayanize
    Commented Aug 2, 2016 at 14:01
1

If you don't have access to the codebase to minify the CSS on your own, you could use a plugin like Better WordPress Minify.

Edit: To minify the value on the fly, you could use minify library

4
  • Thanks. Actually I am adding the textarea in my theme options where users can add their own CSS. But I want in whatever way they add, the output shud be in the minified form
    – Ayanize
    Commented Aug 2, 2016 at 13:30
  • 1
    In that case, you could probably go directly for a PHP implementation of such function. Check the updated answer. Commented Aug 2, 2016 at 13:36
  • If the solution will turn out to be what you were looking for, I'd appreciate if you accepted the answer. Cheers! Commented Aug 2, 2016 at 13:49
  • Thanks mate. So far the code given by Raman Sahasi is working perfectly. Still I am testing. My theme is using a lot of libraries. So I am looking for a php or inline js option. Thanks
    – Ayanize
    Commented Aug 2, 2016 at 13:51

Not the answer you're looking for? Browse other questions tagged or ask your own question.