Saving an array with update_user_meta

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:

Read More
<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.

Related posts

Leave a Reply

1 comment

  1. Change name="days" to name="days[]" for all input fields and use

    update_user_meta( $user_id, 'days', $_POST['days'] );
    

    You 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:

    $values = array_combine( array( 'monday', 'tuesday', 'wednesday', 'thursday', 'friday' ), $_POST['days'] );
    update_user_meta( $user_id, 'days', $values );
    

    For display:

    <?php 
    $days = get_user_meta( $user_id, 'days', true );
    foreach( $days as $day => $checked ):
    ?>
    <input type="checkbox" name="days[]" <?php if( $checked ) echo 'checked="checked"'; ?>>
    <?php endforeach; ?
    

    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 store array( 'monday' => $_POST['monday'], ... ). With this in the database, you can then replace name='days[]' with name="<?php echo $day; ?>"' in the foreach loop.

    Notice I’m using get_user_meta instead of get_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.