I am trying to set the user's display_name and nickname to the first part of the email address of a user (before the @) upon login if nickname is not set.
So far I've got:
add_action( 'wp_login', 'force_nicknames_on_login' );
function force_nicknames_on_login( $username ) {
$user = get_user_by( 'login', $username );
$nickname = get_user_meta( $user->ID, 'nickname', true );
$email = $user_info->user_email;
$email = substr( $email, 0, strpos( $email, "@" ) );
if ( empty ($nickname) ) {
$nickname = $email;
}
if ( ! empty( $nickname ) && ( $user->data->display_name != $nickname ) ) {
$userdata = array(
'ID' => $user->ID,
'nickname' => $nickname,
'display_name' => $nickname,
);
wp_update_user( $userdata );
}
}
Which seems to set the display name up as the nickname if it's already set, but if the user registers without a nickname, it doesn't pull through the email before @.
I am trying to set the user's display_name and nickname to the first part of the email address of a user (before the @) upon login if nickname is not set.
So far I've got:
add_action( 'wp_login', 'force_nicknames_on_login' );
function force_nicknames_on_login( $username ) {
$user = get_user_by( 'login', $username );
$nickname = get_user_meta( $user->ID, 'nickname', true );
$email = $user_info->user_email;
$email = substr( $email, 0, strpos( $email, "@" ) );
if ( empty ($nickname) ) {
$nickname = $email;
}
if ( ! empty( $nickname ) && ( $user->data->display_name != $nickname ) ) {
$userdata = array(
'ID' => $user->ID,
'nickname' => $nickname,
'display_name' => $nickname,
);
wp_update_user( $userdata );
}
}
Which seems to set the display name up as the nickname if it's already set, but if the user registers without a nickname, it doesn't pull through the email before @.
Share Improve this question asked Apr 5, 2019 at 0:36 matthewh86matthewh86 1032 bronze badges1 Answer
Reset to default 2I think you need to rethink your logic that decides to set the empty nickname to the email.
You need to do this, in this order:
- if the nickname is empty, set it to the email (and strip out the part after the '@' if you want.
- then you should have values for display name (whatever they entered), and nickname (whatever they entered, or their email if no entry)
- and then you can store the values
I note that there might be problems with the resultant data, though. The email address might not have a good 'visible' (recognizable?) value for the nickname. There might be some values of emails that wouldn't look good as a nickname.
So perhaps requiring a nickname might be better, or letting the nickname be blank. Perhaps asking for 'first/last name', email, and nickname (visible name). If the visible name is empty, then put in the first/last name. But alert the user that their first/last name will be used, so they may want to enter a nickname. (And then there is the GDPR stuff...)
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745626249a4636823.html
评论列表(0条)