Is any easy method to remove all html comment like <!-- wp_head()--> from source from every pages and posts? Maybe using functions.php? Is any easy method without plugin?

  • I think Autoptimize does this, can you look up how they did it? – kero Jan 24 '18 at 15:37

Here's a quick way to remove all comments using output buffering and preg_replace. We hook in before WordPress starts outputting the HTML to start the buffer. Then we hook in after WordPress stops outputting the HTML to get the buffer and strip the HTML comment tags from the content.

This code would ideally be in it's own plugin. But it could be in your functions.php if you're really adverse to adding more plugins.

namespace StackExchange\WordPress;

//* Start output buffering
function startOutputBuffer() {

//* Print the output buffer
function stopOutputBuffer() {
  $html = ob_get_clean();
  echo strip_html_comments( $html );

//* See note for attribution of this code
function strip_html_comments( string $html ) : string {
  return preg_replace('/<!--(.*)-->/Uis', '', $html);

//* Add action before WordPress starts outputting content to start buffer
add_action( 'wp', __NAMESPACE__ . '\startOutputBuffer' );

//* Add action after WordPress stops outputting content to stop buffer
add_action( 'shutdown', __NAMESPACE__ . '\stopOutputBuffer' );

Note: Regex from this StackOverflow answer by Benoit Villière.


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() {
function buffer_end() {
add_action('get_header', 'buffer_start');
add_action('wp_footer', 'buffer_end');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.