4

Is there a way I can force all users display names to be Firstname Lastname or alternatively change this to be the default?

2 Answers 2

4

This is set during user registration. You can change the value per filter 'user_register'.

Sample code, not tested:

/* Plugin Name: First name plus last name as default display name. */
add_action( 'user_register', 'wpse_67444_first_last_display_name' );

function wpse_67444_first_last_display_name( $user_id )
{
    $data = get_userdata( $user_id );
    // check if these data are available in your real code!
    wp_update_user( 
        array (
            'ID' => $user_id, 
            'display_name' => "$data->first_name $data->last_name"
        ) 
    );
}
6
  • Added to functions.php? Also, is the wpse_67444 part important?
    – Svish
    Oct 7, 2012 at 23:05
  • 1
    I would put it into a separate plugin. The prefix is just a convention on our site to avoid collisions with other code.
    – fuxia
    Oct 7, 2012 at 23:24
  • WordPress newb here, hehe. How would you put it in a separate plugin? Is it just a matter of putting it in a certain file in a certain folder or something?`
    – Svish
    Oct 8, 2012 at 17:49
  • @Svish See my edit. Put the code into a separate file and move it to your plugin directory. Then activate it – done.
    – fuxia
    Oct 8, 2012 at 17:53
  • $data = get_userdata( $userid ); should be $data = get_userdata( $user_id );
    – loQ
    Jul 6, 2016 at 3:40
4

A better solution is to update the display name every time the user is updated. I'm resorting this old thread because I cannot find this solution anywhere.

/* First name as default display name. */
add_action( 'profile_update', 'set_display_name', 10 );

function set_display_name( $user_id ) {

    $data = get_userdata( $user_id );

    if($data->first_name) {

        remove_action( 'profile_update', 'set_display_name', 10 ); // profile_update is called by wp_update_user, so we need to remove it before call, to avoid infinite recursion
        wp_update_user( 
            array (
                'ID' => $user_id, 
                'display_name' => "$data->first_name"
            ) 
        );
        add_action( 'profile_update', 'set_display_name', 10 );
    }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.