An elegant solution to clean up html comments from wordpress themes

Typically, all popular wordpress themes come with html comments to mark endings of div block. This is required for theme developers as it is much easier to see where particular block ends.

However, I do not like leaving code like that in production site. Although some claim that HTML comments have no effect in SEO, it might have effect in keyword discovery process. Additionally, they might have effect for various security plugins, that filter and block content containing bad words.  Third, I think it is bad to leave debug information in production sites.

The biggest problem of these is that WordPress theme frameworks like Hybrid uses these as well. So you will have to clean up frameworks source each time you upgrade your framework. That is not the best approach.

However, You can implement this by creating couple filters in your childs (or custom) theme  functions.php file:

function custom_callback($buffer) {

$buffer=preg_replace('/<!--(.*)-->/Ui',' ',$buffer);

return $buffer;

}

function custom_buffer_start() { ob_start("custom_callback"); }

function custom_buffer_end() { ob_end_flush(); }

if (is_user_logged_in() ) {

} else {

add_action('wp_head', 'custom_buffer_start');

add_action('wp_footer', 'custom_buffer_end');

}

This will clean the code from comments when user is not logged in (for search engines and visitors).

Related posts:

  1. Leaving unmoderated comments? Think again Comments are the basic social feature that most of the sites provide. A comment allows interaction between visitor and owner of website. However, comments pose...
  2. Hacking scissors wordpress plugin: resize based on image ratio Recently, I had simple but interesting problem on wordpress where I could not find ready automatic solution: thumbnail generation based on image ratio. I use...
  3. 5 things to look at when comparing php frameworks I had read a post at sitepoints about 16 php 5 frameworks. I will not argue the fact that frameworks are good and you should...
  4. Antivir Solution pro – new rogue mimicking legitimate antivirus Antivir Solution Pro is a remake of Antimalware Doctor and Antispyware soft. It is a fake antivirus, sharing the name with legitimate Antivir made by...


2 responses to “An elegant solution to clean up html comments from wordpress themes”

  1. Olaf Lederer

    Nice solution but it doesn’t work in WP 3.21 anymore, should this work for comments which are created by plugins too?

Leave a Reply