What should I hook to add extra fields to comments?

First you have to add your input fields to comment form. You can use these two hooks for that:

Here’s how:

function add_my_custom_field_to_comment_form() {
    ?>
    <p class="comment-form-<FIELD_ID>">
            <label for="<FIELD_ID>"><?php _e( 'Your <SOMETHING>', '<TEXTDOMAIN>' ); ?><span class="required">*</span>:</label>

            <input id="<FIELD_ID>" name="<FIELD_ID>" value="" placeholder="" />
        </p>
    <?php
}
add_action( 'comment_form_logged_in_after', 'add_my_custom_field_to_comment_form' );
add_action( 'comment_form_after_fields', 'add_my_custom_field_to_comment_form' );

Then you have to use comment_post hook, to save this value:

function save_my_custom_field_for_comment( $comment_id ) {
    $value = $_POST[ '<FIELD_ID>' ];
    // sanitize the $value
    add_comment_meta( $comment_id, '<FIELD_ID>', $value );
}
add_action( 'comment_post', 'save_my_custom_field_for_comment' );

And then you want to display this value in comment… You can:

  • modify comment callback function so it prints this value too,
  • use comment_text` hook to append this value to the content.

.

function append_my_custom_field_to_comment_content( $comment_text, $comment ) {
    $comment_text = get_comment_meta( $comment->comment_ID, '<FIELD_ID>', true );
    return $comment_text;
}
add_filter( 'comment_text', 'append_my_custom_field_to_comment_content', 10, 2 );

Leave a Comment