Search code examples
phpwordpress

Wordpress: search users using 'first_name' and 'last_name'?


UPDATE: I mean to search user in the Admin User Dashboard at /wp-admin/users.php

Is there a way to search users using 'first_name' and 'last_name'?

I found this plugin but not working at all: https://wordpress.org/plugins/full-name-search-in-wp-admin/

I also found this function, but neither is working in my site. Do I need to call the function with a hook/action?:

function search_users($search_term){

    global $wpdb;
    $the_users = $wpdb->get_results("SELECT DISTINCT $wpdb->users.* FROM $wpdb->users INNER JOIN $wpdb->usermeta um1 ON um1.user_id = $wpdb->users.ID JOIN $wpdb->usermeta um2 ON um2.user_id = $wpdb->users.ID WHERE (um1.meta_key = 'uRPhICRS_capabilities' AND um1.meta_value LIKE '%agent%') AND ((um2.meta_key = 'first_name' OR um2.meta_key = 'last_name') AND um2.meta_value LIKE '%".$search_term."%');");

    if(!empty($the_users)){
        return $the_users;
    }
    else{
        return false;
    }

}

Solution

  • Two Ways as follow:

    1) If You want to check from the string match in either firstname or lastname, following will be work:

    $users_query = new WP_User_Query(
      array(
        'meta_query' => array(
        'relation' => 'OR',
          array(
            'key' => 'first_name',
            'value' => $str,
            'compare' => 'LIKE'
          ),
        array(
            'key' => 'last_name',
            'value' => $str,
            'compare' => 'LIKE'
          )
        )
      )
     );
    
    $users = $users_query->get_results();
    

    2) If you want to check the user from username, user_nicename, user_email, firstname, or lastname use following code:

    //search from the user table 
    $users_query_table = new WP_User_Query(
      array(
        'search' => "*{$str}*",
        'search_columns' => array(
        'user_login',
        'user_nicename',
        'user_email',
      ),
    ) );
    $users_via_table = $users_query_table->get_results();
    
    //search from the usermeta
    $users_query_meta = new WP_User_Query(
      array(
        'meta_query' => array(
        'relation' => 'OR',
          array(
            'key' => 'first_name',
            'value' => $str,
            'compare' => 'LIKE'
          ),
        array(
            'key' => 'last_name',
            'value' => $str,
            'compare' => 'LIKE'
          )
        )
      )
     );
    
    $users_via_meta = $users_query_meta->get_results();
    
    // Merge both result.. 
    $combined_users = array_merge( $users_via_table, $users_via_meta );
    
    // Get unique user
    $users = array_unique( $combined_users, SORT_REGULAR );