Archived topic
Minify Customizer additional CSS output
3 replies · Started by Saurabh on August 28, 2022
Hi David/Tom,
I was wondering if we can minify the output of additional CSS used in the Customizer right out of the box or maybe an option to turn it on?
Most optimization plugins can do it, but why use a plugin when it can be done without one? So I came up with the following code snippet.
// Minify the customizer css output
add_action('wp_head', 'tn_minify_customizer_css_head');
function tn_minify_customizer_css_head(){
remove_action( 'wp_head', 'wp_custom_css_cb', 101 ); //remove the default customizer css output
$buffer = wp_get_custom_css(); //get the customizer css
// search and replace strings
$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
$buffer = str_replace(': ', ':', $buffer);
$buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $buffer);
//add the minified css in wp_head
echo '<style id="wp-custom-css">'.$buffer.'</style>';
}
With limited testing, this works fine for me. Could there be a more efficient way to do it?
Hi there,
aside from saving the CSS in a minified .css file in a child theme, then what you have there is probably the most efficient method of doing that.
Thank you for your suggestion, David.
You're welcome