How to minify HTML in WordPress without a Plugin?

Last update: 21 January 2024
When you minify HTML, unnecessary characters and lines are removed from the source code.
How to minify HTML in WordPress without a Plugin?

HTML does not require indentation, comments, blank lines, etc. They simply make the file easier to read. Removing all this unnecessary material can significantly reduce file size. When you minify the HTML code on your website, the server will send a much smaller page to the client, making your website load faster.

Add code in your file function.php

Tested:
WordPress 6.4.2
PHP 7.4

function wphaf_minify_html( $buffer ) {
  $search = array(
    '/\>[^\S ]+/s',
    '/[^\S ]+\</s',
    '/(\s)+/s',
    '/>\s+\</', # strip whitespaces between tags
    '/<!--(?![^<]*noindex)(.*?)-->/'
  );

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

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

  return $buffer;

}

if( ! is_feed() && ! get_query_var( 'sitemap' ) && ! is_admin() && ! is_user_logged_in() ) {  
  ob_start( 'wphaf_minify_html' );
}