WordPress: Minify HTML for Google PageSpeed

One simple thing you can do to improve the loading speed of WordPress pages is to minify the HTML and then implement a system cache. In this tutorial we will teach you a simple way to minify the HTML code.

Helper Hook

First we have to add a helper hook, this is to affect only the front pages and not to affect the administrative area.

add_action( 'init', 'add_compress_html_hook' );

The Hook

Now we make sure the hook only run in the front-end.

function add_compress_html_hook(){
  if( is_admin( ) )
    return;

  add_action( 'template_redirect', 'compress_html_markup', 1 );
}

Compression

Finally we added compression functions.

function html_minify_buffer( $html ){

  //remove comments
  $html = preg_replace('/<!--(?!\s*(?:\[if [^\]]+]|<!|>))(?:(?!-->).)*-->/s', '', $html);
  $html = preg_replace('/>\s+</', '><', $html);

  return $html;
}

function compress_html_markup( ){
  ob_start( 'html_minify_buffer' );
}

Leave a Reply

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