WordPress – _wp_unfiltered_html_comment causing pages to fail (X)HTML validation

If you have a WordPress blog, and you log in, you may notice pages failing HTML or XHTML validation because of code like this:

<input type="hidden" id="_wp_unfiltered_html_comment" name="_wp_unfiltered_html_comment" value="xxxxxxxxxx" />

This code only shows up if you are logged in, and allows your comments to bypass HTML validation, so you can use whichever HTML tags you like.  What is causing the problem is the “id” attribute.  According to the XHTML standard, the ID must start with a letter, and here it starts with an underscore.

There’s some discussion of this over on the WordPress end, with various opinions.  Depending on which spec you read, it might be valid XHTML.  It’s not super-critical, since no one sees the invalid code besides you.  Still, it looks like it might be fixed in WordPress 2.9.  But until then, my page is going to fail against the validator addon I have in my web browser?

What’s annoying is this code is not part of the WordPress theme, so you cannot fix it without modifying WordPress itself.  That’s not really acceptable, because you’d have to repeat the modification every time a new version of WordPress comes along.

Well, actually, you can fix it in your theme, it’s just a little tricky.  To do it, open the comments.php file in your theme, and find this line:

do_action('comment_form', $post->ID);

Replace it with this:

ob_start();
do_action('comment_form', $post->ID);
$output = ob_get_contents();
ob_end_clean();

echo str_replace(' id="_wp', ' id="wp', $output);

This will strip the underscore from the beginning of the “id” attribute.  Because the do_action() function prints stuff out, we have to capture the output, modify it, and print it.

Since the underscore is still part of the “name” attribute (which does not fail validation), and the “name” attribute is used to build PHP’s $_POST array, I do not think that this modification will have any affect on WordPress’s operation — seems to work as intended when I test it.  And now my pages will validate as well.  Great!

7 thoughts on “WordPress – _wp_unfiltered_html_comment causing pages to fail (X)HTML validation”

  1. Great post!

    Didn’t work for XHTML Strict, but allowed me an easy fix.
    The underscore in the ID validates fine for me, but the input itself is not wrapped in a P tag like the others. (DTD does not allow inputs right inside form tag)

    I changed the last line to echo P tags around the $output and have valid code now.

  2. Thank’s a lot! I could not find any solution of this problem in Russian sources. I guess someone should translate it in russian…

Leave a Reply

Your email address will not be published. Required fields are marked *


*