在 WordPress 中添加到头部时在输出中缩小 CSS

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

我正在从文本区域中添加 CSS。有没有一种方法可以在 <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');

我想要在 <head>

中这样的输出
#logo img{opacity:.8}#header{background-color:red}

提前致谢

如果您无法访问代码库来自行缩小 CSS,您可以使用 Better WordPress Minify.

之类的插件

编辑:要即时缩小值,您可以使用 minify library

您可以结合使用 php heredocs 和 php str_replace...像这样

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');

编辑

如果您从主题选项中获取输出,那么代码将如下所示

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');