It will be a three step process.
-
You can use
comment_form_logged_in_after
(for logged in users) and/orcomment_form_after_fields
(for non-logged in users) actions to add your custom fields. -
Save the values as comment meta using
update_comment_meta
function hooked intocomment_post
action. -
Get the values using
get_comment_meta
.
EDIT: 25-05-2022
Try this..
/*
* This will add the fields to the comment form
*/
function wpse406058_custom_comment_fields() {
echo '<p class="comment-form-wantto">';
echo '<label for="wantto">I Want To</label>';
echo '<select id="wantto" name="wantto" class="myclass">';
echo '<option value="WANT TO BUY">WANT TO BUY</option>';
echo '<option value="WANT TO SELL">WANT TO SELL</option>';
echo '<option value="INFO">INFO</option>';
echo '</select>';
}
add_action( 'comment_form_logged_in_after', 'wpse406058_custom_comment_fields' );
add_action( 'comment_form_after_fields', 'wpse406058_custom_comment_fields' );
/*
* This will field value as comment meta
*/
function wpse406058_save_custom_field($comment_id) {
if ( isset($_POST['wantto']) && !empty($_POST['wantto']) ) {
$wantto = sanitize_text_field($_POST['wantto']);
update_comment_meta( $comment_id, 'wantto', $wantto );
}
}
add_action( 'comment_post', 'wpse406058_save_custom_field' );
Now you can get the value using get_comment_meta( $comment_id, 'wantto', true );
One option to display the value would be filtering the comment text.
function wpse406058_display_comment_meta( $comment_text ) {
$wantto = get_comment_meta( get_comment_ID(), 'wantto', true );
if ( isset($wantto) && !empty($wantto) ) {
$wanttotext="<p class="wantosec">" . esc_html($wantto) . '</p>';
$comment_text = $wanttotext . $comment_text;
}
return $comment_text;
}
add_filter( 'comment_text', 'wpse406058_display_comment_meta' );