I recently was playing with wp_update_user()
. I faced an issue while changing the user_login
key. Others like user_nicename
or other fields change, but user_login
doesn't change even everything looks good. Here is the code I tried so far.
add_action( 'show_user_profile', 'add_new_username_field' );
add_action( 'edit_user_profile', 'add_new_username_field' );
add_action( 'personal_options_update', 'crf_update_profile_fields' );
add_action( 'edit_user_profile_update', 'crf_update_profile_fields' );
function add_new_username_field( $user ) {
$userData = get_userdata( get_current_user_id() );
$username = $userData->user_login;
?>
<h3><?php esc_html_e( 'New Username', 'crf' ); ?></h3>
<table class="form-table" role="presentation">
<tbody>
<tr class="user-email-wrap">
<th>
<label for="new_username"><?php esc_html_e( 'Enter New Username', 'base' ); ?></label>
</th>
<td>
<input class="regular-text ltr" type="text" name="new_username" value="<?php echo $username ?>">
</td>
</tr>
</tbody>
</table>
<?php
}
function crf_update_profile_fields( $user_id ) {
if ( is_user_logged_in() && ! empty($_POST['new_username'])) {
wp_update_user( array( 'ID' => $user_id, 'user_login' => $_POST['new_username'] ) );
// wp_logout();
}
}
Is there something I am missing? Thanks in advance. Note: I purged the cache but doesnt work.