Add new users to "add new user" page on admin's dashboard

I understand there's a lot of similar questions, but all of them show how to update the wp_usermeta table in the database, whereas I want to use wp_update_user() to update a particular field (nickname - user_nicename) in the wp_users table. Here is my snippet, (which I have collected from other similar questions) it appends the new field to the add new user page, but it doesn't save the information in the database with wp_update_user().

P.S.: I also would like to say, as a note, that I can fully grasp the function to append a new field, but I'm completely in the dark about the other one, to save the field, as I can't really understand how the id is captured when you press submit (I just copied and pasted the novo_gravar function and tried to change update_user_meta() with wp_update_user())

?php
add_action( 'user_new_form', 'novo_campo' );

function novo_campo()
{
?    

table class=form-table
    tbody
    tr class=form-field
        th scope=rowlabel for=cpfCPF /label/th
        tdinput name=cpf type=text id=cpf value=/td
    /tr    
    /tbody
/table

?php   
}

//  process the extra fields for new user form
add_action( 'user_register', 'novo_gravar');
function novo_gravar($user_id)
{
    
    wp_update_user(     
                     array( 'ID' = $user_id,
                            'user_nicename' = $_POST['cpf'])
                   );
    
}

Topic actions user-registration Wordpress

Category Web


Check out the source of wp-admin/user-new.php. You'll see WP uses the function edit_user to create the user in the database.

If you inspect the source of edit_user(), you'll see the best candidate is a hook called user_profile_update_errors. We can use that with something like:


function wpse_406364_save_nicename( $errors, $update, $user ) {
    if ( ! $update ) {
        $user->user_nicename = sanitize_text_field( filter_input( INPUT_POST, 'cpf' ) );
    }
}

add_action( 'user_profile_update_errors', 'wpse_406364_save_nicename', 10, 3 );

That will set the user_nicename user field to the value of the cpf POST input, and only on user creation.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.