I have a situation here. I'm writing a custom plugin for WordPress. I'm dealing with an issue:
I'v created a metabox for Custom Post Type with add_meta_box
and with a callback function where I generate a multiselect box. All users showing up with a user ID. The point is: The Custom Post Type is a group and this group can have multiple members (users). The first thing what I tried was saving all the users, which are subscribed to this group, in one single row in the postmeta table but that's not a good solution.
What I want to do now is: Create a new row, for every single user, in the usermeta
table with this key _enroll_user_value_key
.
My field:
echo '<select multiple name="enroll_user_field[]" id="enroll_user_field">';
this values, I want to pass this, for each single selected user, to a new database row in user_meta
. Now I use only this function to save this data: update_user_meta( $enroll_user_data, '_enroll_user_value_key', $post->ID );
But when I select multiple users the row doesn't update or created because there a multiple values passed from the field enroll_user_field[]
.
How could I fix this? Should I create a foreach loop
and repeat the update_user_meta
every single time, for each selected user? And what if I remove a user from the group, should I use a seperate delete function or query for this?
EDIT:
add_meta_box(
'group_member',
'Group members',
'group_members_callback',
'group',
'normal'
);
function group_members_callback( $post ){
wp_nonce_field( 'group_members_save', 'group_members_nonce' );
$values = get_post_meta($post->ID, '_group_members_value_key', true);
$values = explode(',', $values);
echo '<label for="group_members_field">Assign users to this group. If you want to assign multiple users to this module, hold CTRL while you are selecting</label><br /><br />';
echo '<select multiple name="group_members_field[]" id="group_members_field">';
$users = get_users();
foreach( $users as $user ){
if( in_array($user->ID, $values )){
echo '<option selected value="' . $user->ID . '">' . esc_attr( $user->user_email ) . '</option>';
}else{
echo '<option value="' . $user->ID . '">' . esc_attr( $user->user_email ) . '</option>';
}
}
echo '</select>';
}
function group_members_save( $post_id ){
if( ! isset( $_POST['group_members_nonce'] ) ){
return;
}
if( ! wp_verify_nonce( $_POST['group_members_nonce'], 'group_members_save') ){
return;
}
if( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ){
return;
}
if( ! current_user_can('edit_post', $post_id ) ){
return;
}
if( ! isset($_POST['group_members_field'] ) ){
return;
}
$group_members_data = sanitize_text_field( implode(',', $_POST['group_members_field'] ) );
update_post_meta( $post_id, '_group_members_value_key', $group_members_data );
}
add_action('save_post', 'group_members_save');
This line update_post_meta( $post_id, '_group_members_value_key', $group_members_data );
should be update_user_meta
, because I want to save it in the usermeta
table, in seperated rows.