Never Show Login Names as Public Display Names
When a user's public display name is the same as their login name (the WordPress default), switches it to their first and last name, or to a neutral name, so author bylines and comments do not reveal usernames.
Opens WPIDE on
Code
add_filter( 'wp_pre_insert_user_data', function ( $data, $update, $user_id, $userdata ) {
if ( empty( $data['user_login'] ) || empty( $data['display_name'] ) || strtolower( $data['display_name'] ) !== strtolower( $data['user_login'] ) ) {
return $data;
}
$first = isset( $userdata['first_name'] ) ? trim( (string) $userdata['first_name'] ) : '';
$last = isset( $userdata['last_name'] ) ? trim( (string) $userdata['last_name'] ) : '';
if ( $user_id && ! $first && ! $last ) {
$first = (string) get_user_meta( $user_id, 'first_name', true );
$last = (string) get_user_meta( $user_id, 'last_name', true );
}
$name = trim( $first . ' ' . $last );
$data['display_name'] = '' !== $name ? $name : 'Member ' . strtoupper( substr( md5( $data['user_login'] . wp_salt() ), 0, 5 ) );
return $data;
}, 10, 4 );
Notes
Applies when accounts are created or updated; existing accounts change the next time they are saved.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.