Custom comment fields in WordPress

Adding custom fields to comment forms in WordPress doesn’t seem to be documented very well online and I couldn’t find any working plugins either. It’s not difficult at all, though.

Let’s say we want to add a location field to the comment form, and later display the location along with the comment.

First, we’ll need to add the custom location field to the comment form. The function responsible for creating the fields is comment_form(), located in wp-includes/comment-template.php. If you take a look at the code, you’ll see that the default fields are stored in an array, which is later passed through comment_form_defaults filter. To add custom fields, simply add them as new elements to the array, using the filter, like this:

// functions.php
function childtheme_add_custom_fields($fields) {
    // Add a thematic-style field for the commenter location
    $fields['location'] = '<div id="form-section-location">';
    $fields['location'] .= '<div><label for="location">' . __( 'Location' ) . '</label></div>';
    $fields['location'] .= '<div><input id="location" name="location" type="text" size="30" /></div>';
    $fields['location'] .= '</div>';
    return $fields;
}
add_filter( 'comment_form_default_fields', 'childtheme_add_custom_fields' );

Now we’ll need to save the user-submitted data from the newly added field. For this, we will use the comment_post action, called from wp-includes/comments.php. Basically, it’s just an action that’s called between validating the comment data.

To save the data, we’ll use update_comment_meta() – a function for adding metadata to comments.

function childtheme_save_custom_fields($id) {
    // Grab the value of the new field from $_POST and remove html tags
    $comment_location = ( isset($_POST['location']) ) ? trim($_POST['location']) : null;
    update_comment_meta( $id, 'location', $comment_location );
}
add_action( 'comment_post', 'childtheme_save_custom_fields', 10, 1); // last two are priority and number of accepted arguments

To display the location, use something like this (while in the Loop):

$location = esc_html(get_comment_meta(get_comment_ID(), 'team', true));

Note: if your comments template uses the tabindex property, make sure you change the existing values in the template and add the correct values to your new fields. It’s really annoying if the tab key doesn’t work right.

4 thoughts on “Custom comment fields in WordPress

  1. oh man what a life saver, been spending way too many hours trying to get this too work. i have a question though. how do i print out the output?

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>