Wordpress minify html on the main page only

I used this code to minimize HTML output in wordpress. It works great on the main page and on the message page, but in the admin section this causes a lot of problems.

function minify_html(){
    ob_start('html_compress');
}

function html_compress($buffer){

    $search = array(
        '/\n/',         // replace end of line by a space
        '/\>[^\S ]+/s',     // strip whitespaces after tags, except space
        '/[^\S ]+\</s',     // strip whitespaces before tags, except space
        '/(\s)+/s',     // shorten multiple whitespace sequences,
        '~<!--//(.*?)-->~s' //html comments
    );

    $replace = array(
        ' ',
        '>',
        '<',
        '\\1',
        ''
    );

    $buffer = preg_replace($search, $replace, $buffer);

    return $buffer;
}

add_action('wp_loaded','minify_html');

Using 'the_post' instead of 'wp_loaded' only reduces messages, but I would like the main page and mail page to be deleted 100%, but there was nothing in the admin section. How can I combine actions to manage it?

Thank!

+4
source share
1 answer

Nice code, exclude admin:

if (!(is_admin() )) {
function minify_html(){
    ob_start('html_compress');
}

function html_compress($buffer){

    $search = array(
        '/\n/',         // replace end of line by a space
        '/\>[^\S ]+/s',     // strip whitespaces after tags, except space
        '/[^\S ]+\</s',     // strip whitespaces before tags, except space
        '/(\s)+/s',     // shorten multiple whitespace sequences,
        '~<!--//(.*?)-->~s' //html comments
    );

    $replace = array(
        ' ',
        '>',
        '<',
        '\\1',
        ''
    );

    $buffer = preg_replace($search, $replace, $buffer);

    return $buffer;
}

add_action('wp_loaded','minify_html'); }

WP admin works well!

+1
source

All Articles