Created
April 8, 2025 14:51
-
-
Save kimcoleman/3c4f4cf462c933197a12d3c9a30b5547 to your computer and use it in GitHub Desktop.
One-time update: Set user_nicename to a safe "first-name-last-name" format for existing users.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* One-time update: Set user_nicename to a safe "first-name-last-name" format for existing users. | |
*/ | |
function my_update_existing_user_nicenames() { | |
// Only run for admins to avoid performance hits or unauthorized access. | |
if ( ! current_user_can( 'manage_options' ) ) { | |
return; | |
} | |
// Add a transient so we only run this once. | |
if ( get_transient( 'my_updated_user_nicenames' ) ) { | |
return; | |
} | |
$users = get_users(); | |
foreach ( $users as $user ) { | |
$first = get_user_meta( $user->ID, 'first_name', true ); | |
$last = get_user_meta( $user->ID, 'last_name', true ); | |
if ( empty( $first ) || empty( $last ) ) { | |
continue; | |
} | |
$desired_nicename = sanitize_title( $first . '-' . $last ); | |
// Skip if nicename already matches or if it would conflict with others. | |
if ( $user->user_nicename === $desired_nicename ) { | |
continue; | |
} | |
$base_nicename = $desired_nicename; | |
$counter = 1; | |
while ( | |
username_exists( $desired_nicename ) || | |
get_user_by( 'slug', $desired_nicename ) | |
) { | |
$desired_nicename = $base_nicename . '-' . $counter; | |
$counter++; | |
} | |
// Update user_nicename directly. | |
wp_update_user( [ | |
'ID' => $user->ID, | |
'user_nicename' => $desired_nicename, | |
] ); | |
} | |
// Set a transient to mark it as done for 1 year. | |
set_transient( 'my_updated_user_nicenames', true, YEAR_IN_SECONDS ); | |
} | |
add_action( 'admin_init', 'my_update_existing_user_nicenames' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment