Home > OS >  If last name exists else first name | Wordpress
If last name exists else first name | Wordpress

Time:01-07

I'm a completely newbie and trying around in wordpress atm.

I have this function to get first name:

function get_first_name () {
    $user_data = get_userdata(get_current_user_id());
    return  $user_data->first_name; 
}

to get the users first name (and display it somewhere afterwards). Now i want to work it like if the user has registered only with his first name it should only get the first name but if he also registered with lastname it should only (!) get last name and ignore the first name.

Can someone help me with this?

CodePudding user response:

function get_name () {
    $user_data = get_userdata(get_current_user_id());
    
    if(property_exists($user_data, 'last_name')){
        return $user_data->last_name;
    }

    return $user_data->first_name; 
}

This will prevent any errors from trying to access last_name if it is undefined.

CodePudding user response:

A simple ternary statement should do it for you

return $user_data->last_name != '' ? $user_data->last_name : $user_data->first_name;

It is like the longer IF

if ($user_data->last_name != '') {
    return $user_data->last_name;
} else {
    return $user_data->first_name;
}
  •  Tags:  
  • Related