I need to add multiple checkboxes to a post comment form (a Woocommerce product review form, to be exact) that allows people to choose which health condition the product is best for. Upon choosing X number of checkboxes and leaving a written comment, I need those values stored in the commentmeta table as an array. Then I need to print out each selected checkbox value inside that person’s comment as an unordered list.
Where I’m stuck is storing more than one checkbox in commentmeta. Here’s what I have so far for creating the checkboxes:
add_action( 'comment_form_logged_in_after', 'additional_fields' );
add_action( 'comment_form_after_fields', 'additional_fields' );
function additional_fields () {
echo '<p class="comment-form-condition">' .
'<label for="condition">'. __('Conditions') . '<span class="required">*</span>: </label> <br />
<span class="commentconditionbox">';
$conditions = array(
"cancer" => "Cancer",
"crohns" => "Chrons",
"fibromyalgia" => "Fibromyalgia"
);
foreach( $conditions as $condition )
echo '<span class="comment-condition"><input type="checkbox" name="condition" id="condition" value="'. $condition .'"/> '. $condition .'</span>';
echo '</span></p>';
}
Then here’s where I store the data:
add_action( 'comment_post', 'save_comment_meta_data' );
function save_comment_meta_data( $comment_id ) {
if ( ( isset( $_POST['condition'] ) ) && ( $_POST['condition'] != '') )
$filtered_condition = wp_filter_nohtml_kses($_POST['condition']);
add_comment_meta( $comment_id, 'condition', $filtered_condition );
}
This only stores one of the values, though. How do I get it to store the values of each selected checkbox as an array?
Elsewhere in the site, I need to sort products by those values. So, if 2 products have had the Cancer checkbox selected, I’ll output those 2 products on the page by querying which products have that meta value.
Make the
input
names array elements:PHP will convert that on the fly to a real array before you get access to the values.