0

Why am I not allowed to update existing user-meta fields when hooking on to edit_user_profile_update hook? I use this code

add_action( 'edit_user_profile_update', 'xpl_registration_save' );

function xpl_registration_save( $user_id ) {
    $user = get_userdata($user_id);
    $user->add_role( 'gardner' );
    update_user_meta($user_id,'last_name','Smith');
    update_user_meta($user_id,'dogs_name','Sam');
}

This works for the last field, dogs_name, which is added, and updated. But for core fields, some other fields which have been created by another plugin, it doesn't work. How come?

0

You can't change some user meta fields using edit_user_profile_update hook, because it is triggered before processing data from the form. So, you save user's meta to database, then edit form is processed and WP overrides your values. This hook is triggered after each profile edit.

You should use insert_user_meta filter (available since WP v4.4) to change or add user's meta. Filter is applied after user is created/updated, but meta has not yet been saved to the DB.

add_action( 'insert_user_meta', 'se329613_insert_user_meta', 30, 3);

/** 
 * @param array $meta {
 *     Default meta values and keys for the user.
 *
 *     @type string   $nickname
 *     @type string   $first_name
 *     @type string   $last_name
 *     @type string   $description
 *     @type bool     $rich_editing
 *     @type bool     $syntax_highlighting
 *     @type bool     $comment_shortcuts
 *     @type string   $admin_color
 *     @type int|bool $use_ssl
 *     @type bool     $show_admin_bar_front
 * }
 * @param WP_User $user
 * @param bool    $update 
 */
function se329613_insert_user_meta( $meta, $user, $update ) 
{
    // set only when adding a new user
    if ( !$update ) {
        $meta['last_name'] = 'Smith';
        $meta['dogs_name'] = 'Sam';
    }
    return $meta;
}

You can use the user_register action to perform other operations. Functions hooked to user_register are executed when everything is already saved.

add_action( 'user_register' , 'se329613_user_register' );
function se329613_user_register( $user_id ) 
{
    /* some code */
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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