Created
April 8, 2025 14:47
-
-
Save kimcoleman/ac4962be391ed24d24574ea806a2133a to your computer and use it in GitHub Desktop.
Filter the user nicename to use a sanitized first-name-last-name format.
This file contains hidden or 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
<?php | |
/** | |
* Filter the user nicename to use a sanitized first-name-last-name format. | |
*/ | |
function my_set_safe_user_nicename( $nicename ) { | |
if ( ! isset( $_POST['first_name'] ) || ! isset( $_POST['last_name'] ) ) { | |
return $nicename; | |
} | |
$first_name = sanitize_text_field( $_POST['first_name'] ); | |
$last_name = sanitize_text_field( $_POST['last_name'] ); | |
if ( empty( $first_name ) && empty( $last_name ) ) { | |
return $nicename; | |
} | |
$base_nicename = sanitize_title( $first_name . '-' . $last_name ); | |
$new_nicename = $base_nicename; | |
$counter = 1; | |
// Ensure uniqueness. | |
while ( | |
username_exists( $new_nicename ) || | |
get_user_by( 'slug', $new_nicename ) | |
) { | |
$new_nicename = $base_nicename . '-' . $counter; | |
$counter++; | |
} | |
return $new_nicename; | |
} | |
add_filter( 'pre_user_nicename', 'my_set_safe_user_nicename' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment