Minify HTML output

How can I minify my html code?

Minification strips a code file of all data that isn’t required in order for the file to be executed. Minified files don’t need to be decompressed before they can be read, modified or executed.

As minification reduce the file size, it’s good for performance.

Until now I’ve been using a plugin like WP Rocket or the WP-HTML-Compression function from Seth Bergman.

I founded today a simplified solution from PressTigers that fits in 10 lines reproduced below:

<?php
/**
 * Minify HTML output
 */
add_action('get_header', 'wpster_html_minify_start');
function wpster_html_minify_start() {
    ob_start('wpster_html_minyfy_finish');
}
function wpster_html_minyfy_finish($html) {
    $html = preg_replace('/&lt;!--(?!s*(?:[if [^]]+]|!|&gt;))(?:(?!--&gt;).)*--&gt;/s', '', $html);
    $html = str_replace(array("\r\n", "\r", "\n", "\t"), '', $html);
    while (stristr($html, ' ')) $html = str_replace(' ', ' ', $html);
    return $html;
}
?>

Submit a Comment

Your email address will not be published. Required fields are marked *