Using WordPress ‘comment_id_fields’ PHP filter

The comment_id_fields WordPress PHP filter allows you to modify the HTML-formatted hidden ID field comment elements.

Usage

add_filter('comment_id_fields', 'your_custom_function', 10, 3);

function your_custom_function($result, $post_id, $reply_to_id) {
  // your custom code here
  return $result;
}

Parameters

  • $result (string) – The HTML-formatted hidden ID field comment elements.
  • $post_id (int) – The post ID.
  • $reply_to_id (int) – The ID of the comment being replied to.

More information

See WordPress Developer Resources: comment_id_fields

Examples

Modify the comment ID field

Modify the comment ID field by adding a custom class to the input element.

add_filter('comment_id_fields', 'add_custom_class_to_comment_id_fields', 10, 3);

function add_custom_class_to_comment_id_fields($result, $post_id, $reply_to_id) {
  $result = str_replace('<input', '<input class="custom-class"', $result);
  return $result;
}

Add data attributes to the input elements

Add data attributes to the input elements for custom JavaScript handling.

add_filter('comment_id_fields', 'add_data_attributes_to_comment_id_fields', 10, 3);

function add_data_attributes_to_comment_id_fields($result, $post_id, $reply_to_id) {
  $result = str_replace('<input', '<input data-custom-attr="example"', $result);
  return $result;
}

Change input field type to hidden

Change input field type to hidden for a custom comment form.

add_filter('comment_id_fields', 'change_input_field_type_to_hidden', 10, 3);

function change_input_field_type_to_hidden($result, $post_id, $reply_to_id) {
  $result = str_replace('type="text"', 'type="hidden"', $result);
  return $result;
}

Remove the comment-reply-to ID field

Remove the comment-reply-to ID field if not needed in the custom comment form.

add_filter('comment_id_fields', 'remove_comment_reply_to_id_field', 10, 3);

function remove_comment_reply_to_id_field($result, $post_id, $reply_to_id) {
  $pattern = '/<input name="comment_parent" id="comment_parent" type="hidden" value="[\d]+" \/>/';
  $result = preg_replace($pattern, '', $result);
  return $result;
}

Add custom ID to the input elements

Add custom ID to the input elements for easier JavaScript targeting.

add_filter('comment_id_fields', 'add_custom_id_to_input_elements', 10, 3);

function add_custom_id_to_input_elements($result, $post_id, $reply_to_id) {
  $result = str_replace('id="comment_post_ID"', 'id="custom_comment_post_ID"', $result);
  $result = str_replace('id="comment_parent"', 'id="custom_comment_parent"', $result);
  return $result;
}