Remove HTML comments in WordPress

If you check the HTML source from your WordPress website, you will notice a lot of HTML comments. These comments are not visible for visitor and can help the WordPress theme developer while working on his HTML code. Some of you would say: “debugging information shouldn’t be visible to the client”.
There are also plugin developers which place this kind of comments into the code to “mark” their work.

The following WordPress actions are able to filter your code from all HTML comments. Place the PHP code into your functions.php file inside the WordPress theme directory.

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

This kind of output buffering is more memory intensive and might raise your server’s load. Use always a WordPress cache plugin.