Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress minify html only in the main page

I was using this code to minify HTML output in wordpress. It works perfect on the main page and on the post page, but in the admin section it 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' minifies only the posts, but I'd like to be able to minify at 100% the main page, and the post page, but nothing in the admin section. How can I combine the actions in order to manage it?

Thank you!

like image 266
roger.vila Avatar asked Jul 04 '15 10:07

roger.vila


1 Answers

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

It works well WP admin !

like image 81
JBC Avatar answered Oct 25 '22 19:10

JBC