admin管理员组

文章数量:1391987

I am not sure what I am doing wrong here. I am trying to automatically add this metadata to each new user upon registration.

    function add_to_group($user_id, $meta_key, $meta_value ) {
    $userid = get_current_user_id();
    return update_user_meta( $userid, 'learndash_group_users_6597', '6597' );
}


     add_action( ‘user_register’, ‘add_to_group’, 10, 1 );

Any help would be very appreciated.

I am not sure what I am doing wrong here. I am trying to automatically add this metadata to each new user upon registration.

    function add_to_group($user_id, $meta_key, $meta_value ) {
    $userid = get_current_user_id();
    return update_user_meta( $userid, 'learndash_group_users_6597', '6597' );
}


     add_action( ‘user_register’, ‘add_to_group’, 10, 1 );

Any help would be very appreciated.

Share Improve this question asked Feb 26, 2020 at 2:04 CarlenCarlen 31 bronze badge 2
  • How are the users registering? Themselves, or are you adding them? Notice that you're setting the user meta for the current user, not the user that's being registered. They're not necessarily the same thing. – Jacob Peattie Commented Feb 26, 2020 at 2:06
  • @JacobPeattie They are registering themselves using buddypress registration, but I read somewhere you still link to "user_register." – Carlen Commented Feb 26, 2020 at 2:26
Add a comment  | 

1 Answer 1

Reset to default 1

The problem is that you're using get_current_user_id();. There's two reasons this is incorrect:

  1. The user being created is not necessarily the current user. For example, if an admin creates the user manually.
  2. user_register runs immediately after the user is created, but before the user is logged in. So when user_register runs for somebody registering on the front end, there is no current user.

If you want to add meta to the user being created, when they are created, you need to use the $user_id variable that's passed to the callback function. This user ID is for the user that was created, regardless of whether or not they are the currently logged in user.

function add_to_group( $user_id ) {
    update_user_meta( $user_id, 'learndash_group_users_6597', '6597' );
}
add_action( 'user_register', 'add_to_group' );

Note that the $user_id passed to add_to_group is what we are using in update_user_meta().

Also, in your original code you were accepting 3 arguments to the function. I removed them because as you can see from the documentation for the hook, only 1 variable, $user_id is passed to the callback.

本文标签: Adding user metadata to all users