0

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
1

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() {
  ob_start();
}

//* 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.

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.