How to remove HTML comments from the page source

Many plugins inject unnecessary html comments into the page’s HTML. Let’s look at how to remove it.

Why do you want HTML comments in your page’s head tag?

It is a pet hate of mine that HTML get flooded with unnecessary tripe, such as comments. In WordPress, loads of plugins dump this crap into the page, but why? My opinion, as a programmer, is that this has no place in a live site. Sure, if you feel the need to output them for debugging purposes, in development/staging, then do so – though I’m still not sure why you’d do that, as there are proper debugging tools and techniques for that. But a live site should be optimised; only transmitting data that are necessary for the presentation and functionality of the site.

Here’s an example of how to remove comments from, that Yoast injects:

/**
* Disable Yoast's comments 
*/
add_action('template_redirect', function () {if (!class_exists('WPSEO_Frontend')) return;

// set probable method (Yoast update this from time-to-time)
$method = 'debug_mark';

// get instance
$instance = WPSEO_Frontend::get_instance();

// abort is the method doesn't exist
if (!method_exists($instance, $method)) return;

// remove the method
remove_action('wpseo_head', [$instance, $method], 2);
}, 9999);

Remove all HTML comments

The above code snippets only address the comments in the head tag by a single plugin. There are techniques to remove all comments from the page, this can be achieved in several ways. One way is to buffer all the page source and use a regular expression to remove anything between <!-- and -->, before outputting the content of the buffer. Note, this is not a recommened apprach, as it will probably slow your site, unless you cached the results. Nonetheless, here’s a theoretical solution (untested):

function buffer_callback($buffer) {
    return preg_replace('/<!--(.|s)*?-->/', '', $buffer);
}
add_action('get_header', function () {
    ob_start('buffer_callback');
});
add_action('wp_footer', function () {
    ob_end_flush();
});

Reply