egr103 egr103 - 1 month ago 9
PHP Question

Add & store extra fields - Wordpress Comments

I am using the standard Wordpress Comment Form but I would like to add radio buttons as an additional field to the form, like so:

enter image description here

My PHP to generate the standard form is as follows but I don't know the best route to add, store and show (on the front end) the additional information:

<?php
$fields = array(
'author' =>
'<p class="comment-form-author"><label for="author">' . __( 'Name', 'domainreference' ) . '</label> ' .
( $req ? '<span class="required">*</span>' : '' ) .
'<input id="author" name="author" placeholder="Enter your name" type="text" value="' . esc_attr( $commenter['comment_author'] ) . '" size="30"' . $aria_req . ' /></p>',

'email' =>
'<p class="comment-form-email"><label for="email">' . __( 'Email', 'domainreference' ) . '</label> ' .
( $req ? '<span class="required">*</span>' : '' ) .
'<input id="email" name="email" placeholder="Enter your email address" type="text" value="' . esc_attr( $commenter['comment_author_email'] ) . '" size="30"' . $aria_req . ' /></p>',

'comment_field' =>
'<p class="comment-form-comment"><label for="comment">' . _x( 'Comment', 'noun' ) .
'</label><textarea id="comment" placeholder="Enter your comment" name="comment" cols="45" rows="8" aria-required="true">' .
'</textarea></p>'
);

$args = array(
'id_form' => 'commentform',
'class_form' => 'comment-form',
'id_submit' => 'submit',
'class_submit' => 'submit btn',
'name_submit' => 'submit',
'title_reply' => __( 'Leave a Reply' ),
'title_reply_to' => __( 'Leave a Reply to %s' ),
'cancel_reply_link' => __( 'Cancel Reply' ),
'label_submit' => __( 'Post Comment' ),
'format' => 'xhtml',

'fields' => apply_filters( 'comment_form_default_fields', $fields )

);

comment_form( $args ); ?>

Answer

Turns out Advanced Custom Fields, a plugin I was already using, makes it super easy to insert additional fields into the comment form.

ACF is so good that it has created a tutorial to do just this and how to output the data within the comment thread: https://www.advancedcustomfields.com/resources/get-values-comment/

However, by doing this the plugin adds a bunch of superfluous CSS and JS files to the front end so to remove these, add this bit of code to your functions.php:

// disable acf css on front-end acf forms
add_action( 'wp_print_styles', 'my_deregister_styles', 100 );

function my_deregister_styles() {
  wp_deregister_style( 'acf' );
  wp_deregister_style( 'acf-field-group' );
  wp_deregister_style( 'acf-global' );
  wp_deregister_style( 'acf-input' );
  wp_deregister_style( 'acf-datepicker' );
}
Comments