update post meta using user_register hook not working

The part that does not work in your code is not adding or updating the post meta, but getting the user meta named team which you’re retrieving via um_user().

And that’s because as @WebElaine pointed, by the time the user_register hook is fired, the custom field team has not yet added to the database (neither by WordPress nor UM), hence um_user( 'team' ) returns nothing/false.

But if you want to use the user_register hook to add/update the post meta, you can use the $_POST['team'] value submitted via the form. So replace this:

$groupItem = get_post(um_user('team'));

with this:

if ( $post_id = um_user( 'team' ) ) {
    $groupItem = get_post( $post_id );
// I'm just doing a basic validation, but you should try to make it better!
} elseif ( ! empty( $_POST['team'] ) ) {
    $groupItem = get_post( absint( $_POST['team'] ) );
}

Or since you’re relying upon the team meta which came from user input submitted via the UM’s registration form, then it might better to use um_registration_complete hook to add/update the post meta:

  1. First, call um_fetch_user() before you call um_user():

    um_fetch_user( $user_id ); // set the user
    $groupItem = get_post( um_user( 'team' ) );
    

    Alternatively, you can use get_user_meta():

    $post_id = get_user_meta( $user_id, 'team', true );
    $groupItem = get_post( $post_id );
    
  2. And replace the add_action('user_register', 'gs_add_user_to_group', 10, 1); with this:

    add_action( 'um_registration_complete', 'gs_add_user_to_group', 10, 2 );
    

Tried & tested working on WordPress 5.3.2 with UM 2.1.4.

Leave a Comment