How we can get the user id by its display_name

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?

Related posts

Leave a Reply

5 comments

  1. 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.

  2. 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;
    }
    
  3. 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 );
    
  4. 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;
    }