WordPress introduced a new function in 3.0 called
comment_form(). With it you can easily filter different parts of the default comment form to output whatever you’d like including added placeholders.
In case you didn’t know, HTML5 placeholders are those sweet labels inside the input field that disappear when you start typing:
The codex page is incomplete, so it took a little digging to figure out how to add placeholders. Here’s how you can add HTML5 placeholders to all your comment form fields that will work across a wide range of browsers including all the way back to IE6.
Learn how to create your first WordPress theme from scratch in my upcoming course: View the course.
Updating the Default Comment Fields
You should have
comment_form() somewhere in your comments.php file outputting the comment form. We’re going to leave it just how it is and use filters to edit the output.
In your functions file, add the following function:
The function above hooks into the
comment_form_default_fields filter which is run before WordPress outputs the default comment form fields (name, email, url).
my_update_fields accesses the $fields array to change the the author, email, and url inputs and then returns the updated $fields.
There are a few updates to the comment form here:
1) The email and website inputs now use their HTML5 input type. For instance, the email input uses
type="email" which improves the mobile experience and makes for easier styling because you can target it by the type attribute.
2) A min & max length were added to the name field (which of course can be modified or removed easily if you want).
3) Lastly, the placeholders have been added. You can set them to say anything you’d like.
While we’re at it we may as well update the actual comment field to add a placeholder with some encouraging text to visitors.
Here’s that code:
The above function hooks into the
comment_form_field_comment filter made specifically to update the comment textarea.
Cross Browser Compatibility
We’re almost done, but there’s one thing I didn’t mention with the code above: it removes the labels. You can add them back, but I find them unnecessary and complicated when placeholders could be used.
You’ve now got working HTML5 placeholders in your comment form. If you want to learn more about customizing the comment form, 1stWebDesigner has a really comprehensive article on the subject you should check out.