Save meta box values as an array to wp_postmeta

In PHP, there is no need to use the square brackets that are required in an HTML form name to indicate an array, such as you get when using checkboxes.

In other words, this in HTML:

<label><input type="checkbox" name="brand[]" value="1"> Brand 1</label> <label><input type="checkbox" name="brand[]" value="2"> Brand 2</label> <label><input type="checkbox" name="brand[]" value="3"> Brand 3</label>

Will be set as $_POST['brand'] in PHP, the value of which is an array with a count of 3, indexed from 0 to 2, assuming that all three boxes are checked (only checked boxes will be part of the $_POST['brand'] array).

So we can’t treat that post variable as a string, either, since it is an array and WordPress needs it to be an array to properly serialize its value when it’s inserted into the database.

So, the correct code to set it as a metadata value is:

if( isset( $_POST[ 'brand' ] ) ) {
    update_post_meta( $post_id, 'brand', array_map( 'sanitize_text_field', $_POST[ 'brand' ] ) );
}

WordPress will automatically serialize the array for you, so when you retrieve that metadata key-value pair using get_post_meta, the value of brand will also be an array with a count of 3, indexed from 0 to 2 (again, if all three checkboxes were checked).

All that said, you might want to create a better callback function for array_map than just sanitize_text_field; that is, you may want to ensure that the values in $_POST['brand'] match your expected type and range.

For example, if you need integers and get letters, it doesn’t do you any good to save that bad data.