Home > Software design >  Force first name as display name in Wordpress
Force first name as display name in Wordpress

Time:10-16

Struggling to find a solution to force the users' first name to be also their display name.

I found this. It's not perfect as it changes the FN LN to be the display name, I tried to edit it, but didn't work.

add_action ('admin_head','make_display_name_f_name_last_name');
function make_display_name_f_name_last_name(){
   $users = get_users(array('fields'=>'all'));
   foreach($users as $user){
      $user = get_userdata($user->ID);
      $display_name = $user->first_name . " " . $user->last_name;
      if($display_name!=' ') 
         wp_update_user( array ('ID' => $user->ID, 'display_name' => $display_name) );
      else 
         wp_update_user( array ('ID' => $user->ID, 'display_name' => $user->display_login) );
      if($user->display_name == '')
         wp_update_user( array ('ID' => $user->ID, 'display_name' => $user->display_login) );
   }
}

CodePudding user response:

You can simplify it as

add_action('admin_head', function () {
    foreach (get_users(['fields' => 'all']) as $user) {
        $userData = get_userdata($user->ID);
        wp_update_user(['ID' => $user->ID, 'display_name' => $userData->first_name ?: $user->display_login]);
    }
});

or even smaller as

add_action('admin_head', fn() => array_reduce(get_users(['fields' => 'all']), fn ($carry, $user) =>
    wp_update_user(['ID' => $user->ID, 'display_name' => get_userdata($user->ID)->first_name ?: get_userdata($user->ID)->display_login])
));

Update

Answer was updated to fallback display_login according to vee's comment:

Be careful! First name in WordPress can be empty. With your current code, it can be empty display name.

  • Related