Wordpress Change Default Display Name Publicy As for all existing users

<?php

//Sets the user's display name (always) to first name last name, when it's avail.
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) );
    }   
}

?>

A old question but my answer might be usefull for someone else.

Run this query on your database (adjust table names if you have another prefix):

UPDATE wp_users SET display_name = CONCAT((SELECT meta_value FROM wp_usermeta WHERE meta_key = 'first_name' AND user_id = ID), ' ', (SELECT meta_value FROM wp_usermeta WHERE meta_key = 'last_name' AND user_id = ID));

On WP 3.3.1 but should work on later versions.


Problem with using the admin_head hook is that it doesn't work for users who don't use the admin system. Also, my attempts to implement the solution posted by Marty failed because it doesn't seem that the display_name can be updated by update_user_meta() - you have to use wp_update_user().

My proposal - put this in your functions.php file:

function force_pretty_displaynames($user_login, $user) {

    $outcome = trim(get_user_meta($user->ID, 'first_name', true) . " " . get_user_meta($user->ID, 'last_name', true));
    if (!empty($outcome) && ($user->data->display_name!=$outcome)) {
        wp_update_user( array ('ID' => $user->ID, 'display_name' => $outcome));    
    }
}
add_action('wp_login','force_pretty_displaynames',10,2); 

For me (using WP 3.4.1), that works OK, replacing the display name as soon as they log in.


Here's an improved version of richplane's answer that works in newer versions of WordPress (3.8+):

/**
* Format WordPress User's "Display Name" to Full Name on Login
* ------------------------------------------------------------------------------
*/

add_action( 'wp_login', 'wpse_9326315_format_user_display_name_on_login' );

function wpse_9326315_format_user_display_name_on_login( $username ) {
    $user = get_user_by( 'login', $username );

    $first_name = get_user_meta( $user->ID, 'first_name', true );
    $last_name = get_user_meta( $user->ID, 'last_name', true );

    $full_name = trim( $first_name . ' ' . $last_name );

    if ( ! empty( $full_name ) && ( $user->data->display_name != $full_name ) ) {
        $userdata = array(
            'ID' => $user->ID,
            'display_name' => $full_name,
        );

        wp_update_user( $userdata );
    }
}

Tags:

Wordpress