0

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="row"><label for="cpf">CPF </label></th>
        <td><input 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'])
                   );
    
}

1 Answer 1

1

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.

1
  • Thanks a lot! Actually, the snippet was working, what happened was I was looking to the dashboard nickname and thinking that echoed the database entry for the user_nicename, whereas it really echoes a usermeta field called nickname. When I looked directly at the database I could see the mistake. Your answer is way more ellegant, though! Thanks a lot for the input!
    – Assunivasf
    Commented Jun 9, 2022 at 19:13

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.