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');
Sign up to request clarification or add additional context in comments.

2 Comments

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.
Yes yes. I got it like this. Thanks once again. It's working lovely.
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 Comments

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
In that case, you could probably go directly for a PHP implementation of such function. Check the updated answer.
If the solution will turn out to be what you were looking for, I'd appreciate if you accepted the answer. Cheers!
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.