I have been trying to add to the default WordPress comment form. I need to add placeholder=”” to each field. I can’t figure out the filter. I don’t get any errors but I don’t see the placeholder either.
After searching the posts here for an hour, I came up with this so far
function my_fields($args){
$commenter = wp_get_current_commenter();
$user = wp_get_current_user();
$user_identity = $user->exists() ? $user->display_name : '';
$req = get_option( 'require_name_email' );
$aria_req = ( $req ? " aria-required='true'" : '' );
$fields['author'] = '<input id="author" placeholder="name" name="author" type="text" value="'
. esc_attr( $commenter['comment_author'] ) . '" size="30"' . $aria_req . ' /></p>';
return $args;
}
add_filter('comment_form', 'my_fields');
I have tried many different variations and tried returning many different things but am having no luck.
You should filter 'comment_form_default_fields'
to add the placeholder
attribute.
Sample code
add_filter( 'comment_form_default_fields', 'wpse_62742_comment_placeholders' );
/**
* Change default fields, add placeholder and change type attributes.
*
* @param array $fields
* @return array
*/
function wpse_62742_comment_placeholders( $fields )
{
$fields['author'] = str_replace(
'<input',
'<input placeholder="'
/* Replace 'theme_text_domain' with your theme’s text domain.
* I use _x() here to make your translators life easier. :)
* See http://codex.wordpress.org/Function_Reference/_x
*/
. _x(
'First and last name or a nick name',
'comment form placeholder',
'theme_text_domain'
)
. '"',
$fields['author']
);
$fields['email'] = str_replace(
'<input id="email" name="email" type="text"',
/* We use a proper type attribute to make use of the browser’s
* validation, and to get the matching keyboard on smartphones.
*/
'<input type="email" placeholder="contact@example.com" id="email" name="email"',
$fields['email']
);
$fields['url'] = str_replace(
'<input id="url" name="url" type="text"',
// Again: a better 'type' attribute value.
'<input placeholder="http://example.com" id="url" name="url" type="url"',
$fields['url']
);
return $fields;
}
Result

Some notes
- Do not use the placeholder as a replacement for
label
. Screen reader users will get very angry. And it is not allowed anyway.
- I have changed the
type
attribute too. This will help your visitors more than a placeholder
.
- Make sure the fields don’t look already filled out. But try to get a readable contrast. Yes, that’s not easy. You can use some CSS, but it doesn’t work in all browsers.