Add Comment Custom Field

I searched a lot of thread regarding my problem, but unfortunately I found nothing works, and this my final option. I want to add some custom fields on my comment form. How can I do that?

2 Answers
2

Here you go: Adding Custom Fields to WordPress Comment Forms?

And another awesome post on this: http://wpengineer.com/2214/adding-input-fields-to-the-comment-form/

Functions are available to add/update, delete comment meta, similar to post and user meta.

Edit:
Here’s an example to give you a start (put the code into the functions.php or in a custom plugin):

Add the fields to comment form:

add_filter( 'comment_form_defaults', 'change_comment_form_defaults');
function change_comment_form_defaults( $default ) {
    $commenter = wp_get_current_commenter();
    $default[ 'fields' ][ 'email' ] .= '<p class="comment-form-author">' .
                                            '<label for="city">'. __('City') . '</label>
                                        <span class="required">*</span>
                                        <input id="city" name="city" size="30" type="text" /></p>';
    return $default;
}

4 functions to retrieve/add/update/delete comment meta:

get_comment_meta( $comment_id, $meta_key, $single = false );
add_comment_meta($comment_id, $meta_key, $meta_value, $unique = false );
update_comment_meta($comment_id, $meta_key, $meta_value, $unique = false );
delete_comment_meta( $comment_id, $meta_key, $single = false );

This is where you’d do the validations:

add_filter( 'preprocess_comment', 'verify_comment_meta_data' );
function verify_comment_meta_data( $commentdata ) {
    if ( ! isset( $_POST['city'] ) )
        wp_die( __( 'Error: please fill the required field (city).' ) );
    return $commentdata;
}

And save the comment meta:

add_action( 'comment_post', 'save_comment_meta_data' );
function save_comment_meta_data( $comment_id ) {
    add_comment_meta( $comment_id, 'city', $_POST[ 'city' ] );
}

Retrieve and display comment meta:

add_filter( 'get_comment_author_link', 'attach_city_to_author' );
function attach_city_to_author( $author ) {
    $city = get_comment_meta( get_comment_ID(), 'city', true );
    if ( $city )
        $author .= " ($city)";
    return $author;
}

(Note: All the code is from the WPengineer link I posted above. There are more details and advanced usages in that post, please check them too! )

Leave a Comment