1

I have user display_name and with this I want to get the id of that user.

So, how can I get the user id?

3

You can use the following function:

function get_user_id_by_display_name( $display_name ) {
    global $wpdb;

    if ( ! $user = $wpdb->get_row( $wpdb->prepare(
        "SELECT `ID` FROM $wpdb->users WHERE `display_name` = %s", $display_name
    ) ) )
        return false;

    return $user->ID;
}

This is the same code get_user_by() uses, but since that function only allows ID, slug, email or login we have to create a new function.

1

Use WP_User_Query.

$args= array(
  'search' => 'Display Name', // or login or nicename in this example
  'search_fields' => array('user_login','user_nicename','display_name')
);
$user = new WP_User_Query($args);

Just answered one very similar to this: How we can get the author ID by its Name

1

Completely untested, but I can't see anything in the code why it wouldn't work to use get_users() with a meta query:

$users = get_users( array(
    'meta_key' => 'display_name',
    'meta_value' => 'John Doe'
) );

$user = ( ( isset( $users[0] ) ? $users[0] : false );

$user_id = ( $user ? $user->ID : false );
  • 1
    display_name is not on the usermeta table but is a dedicated column the users table. – Peter Bushnell Jan 10 '17 at 14:37
1

I do not think that this has been mentioned, probably because it searches display_name as well as email address, URL, ID and username, this is more than required but worked well for my particular use case.

function get_user_id_by_search( $search_term ) {
    $user = get_users(array('search' =>  $search_term));

    if (!empty($user))
        return $user[0]->ID;
}
0

the wordpress user query by default doesn't allow the display_name in search column even it's added in , here is a solution http://manchumahara.com/2014/04/03/search-user-by-display-name-in-wordpress-sitewide/

Example:

$args= array(
  'search' => 'Display Name', // or login or nicename in this example
  'search_fields' => array('user_login','user_nicename','display_name')
);
$user = new WP_User_Query($args);

The above query will not find for display_name

you need to use this filter

add_filter('user_search_columns', 'user_search_columns_bd' , 10, 3);

function user_search_columns_bd($search_columns, $search, $this){

    if(!in_array('display_name', $search_columns)){
        $search_columns[] = 'display_name';
    }
    return $search_columns;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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