Snippet: Add extra field in comment form

Add following snippet to “functions.php”

Snippet

add_filter( 'comment_form_defaults', 'add_extra_comment_form_field'); // Displaying field
add_filter( 'preprocess_comment', 'verify_comment_meta_data' ); // Verifying the data
add_action( 'comment_post', 'save_comment_meta_data' );
add_filter( 'get_comment_author_link', 'attach_location_to_author' ); // Retrieving and displaying the data

// Displaying field
function add_extra_comment_form_field( $default ) {
    $commenter = wp_get_current_commenter();
    $default[ 'fields' ][ 'email' ] .= '<p class="comment-form-author">' .
        '<label for="Location">'. __('Location') . '</label>
        <span class="required">*</span>
        <input id="location" name="location" size="30" type="text" /></p>';
    return $default;
}
// Verifying the data
function verify_comment_meta_data( $commentdata ) {
    if ( ! isset( $_POST['location'] ) )
        wp_die( __( 'Error: please fill the required field (location).' ) );
    return $commentdata;
}
//Saving in database
function save_comment_meta_data( $comment_id ) {
    add_comment_meta( $comment_id, 'location', $_POST[ 'location' ] );
}
//Retrieving and displaying the data
function attach_location_to_author( $author ) {
    $city = get_comment_meta( get_comment_ID(), 'location', true );
    if ( $location)
        $author .= " ($location)";
    return $author;
}

Result

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=""> <strike> <strong>