How to replace username with email address in users table

I have a custom built site that does not use usernames and everything requires use of their email address. The username is auto generated and looks bad in the table.

I know there are filters and actions to work with custom columns within the users table but I have been looking for a way to replace the username with the email address.

I know I can unset the username using manage_users_columns filter but I then loose the row actions.

Is there a way to accomplish this without rewriting wordpress core functions?

Edit - Clarification: I am looking to replace the username column in the users.php table.

Topic filters wp-admin users Wordpress

Category Web


It seems that the username column content is hardcoded in single_row() of WP_Users_List_Table and there isn't a filter you can use to change it.

A hacky way is to enqueue some javascript on the users view and have the script change the content.

Or take the rocky road by duplicating the code that handles the row actions in single_row(), and replace the default column with a custom one showing the email and the actions.

Or just brute force the email as the username with wp_pre_insert_user_data filter.


function wpse406344_replace_usernames() {
    
    //Get all the users
    $users = get_users();
    
    //Loop through them and update user_login table
    foreach( $users as $user ) {
        wp_insert_user(array(
            'ID' => $user->ID,
            'user_login' => $user->user_email,
        ));
    }
    
}
add_action( 'init', 'wpse406344_replace_usernames' );

You need to run this only once. After successful execution, remove this. Also note, this will only update existing users. If you want to set username for future registrations, you can use the user_register hook.

About

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