how to add custom field in comment form in wordpress

To add a custom field in the WordPress comment form, follow these steps:

  1. Open your theme's functions.php file:
function custom_comment_form_field() {
    // Add your custom field HTML here
}
add_action('comment_form_logged_in_after', 'custom_comment_form_field');
add_action('comment_form_after_fields', 'custom_comment_form_field');
  1. Inside the custom_comment_form_field function, add the HTML for your custom field:
function custom_comment_form_field() {
    echo '<p class="comment-form-custom-field">
        <label for="custom_field">Custom Field</label>
        <input type="text" name="custom_field" id="custom_field" />
    </p>';
}
  1. Save the changes to your functions.php file.

  2. If you want to save and display the custom field value, modify the comment_text function:

function save_comment_meta_data($comment_id) {
    if (isset($_POST['custom_field'])) {
        $custom_field_value = sanitize_text_field($_POST['custom_field']);
        add_comment_meta($comment_id, 'custom_field', $custom_field_value);
    }
}
add_action('comment_post', 'save_comment_meta_data');
  1. If you want to display the custom field value, you can use the following code:
function display_comment_meta_data($comment_text, $comment) {
    $custom_field_value = get_comment_meta($comment->comment_ID, 'custom_field', true);
    if (!empty($custom_field_value)) {
        $comment_text .= '<p>Custom Field: ' . esc_html($custom_field_value) . '</p>';
    }
    return $comment_text;
}
add_filter('comment_text', 'display_comment_meta_data', 10, 2);
  1. Save the changes to your functions.php file.

Now, the custom field should appear in the comment form, and its value will be saved and displayed when users leave comments.