Skip to content

Instantly share code, notes, and snippets.

@pattihis
Last active April 6, 2021 21:07
Show Gist options
  • Save pattihis/0fe985b5d1e653af5aeee2597ac5ab88 to your computer and use it in GitHub Desktop.
Save pattihis/0fe985b5d1e653af5aeee2597ac5ab88 to your computer and use it in GitHub Desktop.
Shortcode to edit all Wordpress users: change user_login based on email username and populate display_name/nickname
<?php
function edit_all_users($atts) {
global $wpdb;
$output = '<ol>';
foreach( get_users() as $user ) {
$username = get_user_by( 'id', $user->ID )->user_login;
$email = get_user_by( 'id', $user->ID )->user_email;
$pos = strpos($username, '@');
if ($pos !== false) {
$parts = explode('@', $email);
$username = $parts[0];
if ( username_exists( $username ) || ( strlen($username) < 4 ) ) {
$username = $username . '_' . rand(0, 9999);
}
}
$wpdb->update($wpdb->users, array('user_login' => $username), array('ID' => $user->ID));
$public = ( empty($user->first_name) ) ? $username : $user->first_name . ' ' . $user->last_name;
$user_data = wp_update_user( array( 'ID' => $user->ID, 'display_name' => $public ) );
$user_data = wp_update_user( array( 'ID' => $user->ID, 'nickname' => $public ) );
if ( is_wp_error( $user_data ) ) {
$output .= '<li>ERROR !!</li>';
} else {
$output .= '<li>'. $email . ' -> '. $username .'</li>';
}
}
return $output.'</ol>';
}
add_shortcode('edit-users', 'edit_all_users');
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment