I have added more fields to the user information, but now I’m struggling with saving an array of values.
How I display the values:
<tr>
<th><label for="days">days</label></th>
<td>
<input type="checkbox" name="days" value="<?php echo esc_attr( get_the_author_meta( 'monday', $user->ID ) ); ?>"> Monday<br>
<input type="checkbox" name="days" value="<?php echo esc_attr( get_the_author_meta( 'tuesday', $user->ID ) ); ?>"> Tuesday<br>
<input type="checkbox" name="days" value="<?php echo esc_attr( get_the_author_meta( 'wednesday', $user->ID ) ); ?>"> Wednesday<br>
<input type="checkbox" name="days" value="<?php echo esc_attr( get_the_author_meta( 'thursday', $user->ID ) ); ?>"> Thursday<br>
<input type="checkbox" name="days" value="<?php echo esc_attr( get_the_author_meta( 'friday', $user->ID ) ); ?>"> Friday<br>
</td>
</tr>
How I’m saving the values:
update_user_meta($user_id, 'days', $_POST['monday, tuesday, wednesday, thursday, friday']);
I know I’m doing it wrong, but I can’t find the right way to do it. I hope someone here can help me.
Change
name="days"
toname="days[]"
for all input fields and useYou will be storing a numeric array with true/false values depending on if those fields were checked or not.
To set the pre-set the value of a checkbox you can’t simply set its value to what you desire. The right attribute to do that is
checked="checked"
. Here’s an example of how you could go about this in its entirety:For display:
But in fact, in your case, using an array for field name is just clumsy. You could just name each field “monday”, “tuesday” and so on, retrieve the value with
$_POST['monday']
for example, and then storearray( 'monday' => $_POST['monday'], ... )
. With this in the database, you can then replacename='days[]'
withname="<?php echo $day; ?>"'
in the foreach loop.Notice I’m using
get_user_meta
instead ofget_author_meta
– they are not interchangeable!The WordPress API may be a small hurdle for you but I think that what you really need to study up on is just how to build forms and how to process them with PHP. Hopefully this can be a start, but there is a lot more material on the Internet.