WordPress: search users using ‘first_name’ and ‘last_name’?

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 );

Leave a Comment