0

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.

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

1 Answer 1

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.

1
  • You are amazing! Thank you for explaining this to me. I was trying to work off the wordpress documentation, but as you can see am still new to php. I really appreciate the explanation as well as the working code.
    – Carlen
    Commented Feb 26, 2020 at 4:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.