1

I found filter hooks to add/modify the WordPress default comment form. But I couldn't find how to add extra fields to a CPT's (custom post type) comment form.

I actually want to know the right way of adding extra input fields like "Rating" field, "First name" field, "Last name" field etc to a custom post type's comment form.

2

If you have already found the filter inside the comment_form function, you are quite close. There is a filter called comment_form_default_fields which allows you to add extra input fields to the array of fields, which normally holds name, mail address and url. You use it like this (in your theme's functions.php):

add_filter ('comment_form_default_fields','wpse270550_add_field');
function wpse270550_add_field ($fields) {
  $fields['your_field'] = '<p><label for="your_field">Your Label</label><input id="your_field_id" name="your_field" type="text" value="" size="30"/></p>';
  return $fields;
  }

The only thing you have to if you want to add this field only to comment forms of a certain CPT is to add a conditional:

add_filter ('comment_form_default_fields','wpse270550_add_field', 10, 1);
function wpse270550_add_field ($fields) {
  if ('your_cpt' == get_post_type())
    $fields['your_field'] = '<p><label for="your_field">Your Label</label><input id="your_field_id" name="your_field" type="text" value="" size="30"/></p>';
  return $fields;
  }

Beware that the above only adds the field in the form on the user end. You will also want the field to be stored in the database once it is submitted. For this you will have to hook into the comment_post action like this:

add_action ('comment_post', 'wpse270550_add_comment_meta_value', 10, 1);
function wpse270550_add_comment_meta_value ($comment_id) {
    if(isset($_POST['your_field'])) {
        // sanitize data
        $your_field = wp_filter_nohtml_kses($_POST['your_field']);
        // store data
        add_comment_meta ($comment_id, 'your_field', $your_field, false);
        }
    }
  • This answer really helps me out. Now, one question on my mind. How can I get the value of the "your_field" field? I tried with $_POST['your_field'] to get the value. But not working. – Eh Jewel Jun 20 '17 at 4:25
  • you would need get_comment_meta for that. – cjbj Jun 20 '17 at 9:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.