how to update current logged user username

I need to keep in sync the username and the email of my users. I don't know if there is a better way so I have tried running this code right after the user updates his profile data:

global $wpdb;
$wpdb-update(
    $wpdb-users,
    array('user_login' = $email),
    array('ID' = $user-ID)
);

but this way the auth cookie becomes invalid and the user is logged out.

I have also tried forcing the creation of the auth cookie right after the update, like this:

wp_clear_auth_cookie();
$user = get_user_by( 'id', $user_id ); 
if( $user ) {
    wp_set_current_user( $user_id, $user-user_login );
    wp_set_auth_cookie( $user_id, true );
    do_action( 'wp_login', $user-user_login );
}

but with no results.

Topic authentication user-access login Wordpress

Category Web


Try hooking in as soon as the user is created or updated.

<?php

function wpse_250785_sync_user_login_with_email($user_id) {
    $user = new WP_User($user_id);

    if ($user->user_login != $user->user_email) {
        $user->user_login = $user->user_email;
        wp_update_user($user);
    }
}
add_action('user_register', 'wpse_250785_sync_user_login_with_email');
add_action('profile_update', 'wpse_250785_sync_user_login_with_email');

Disclaimer: Untested, but should work ;)

About

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