How can I search users by username, email address, first name, and last name in WordPress?

I am working on a WordPress theme where I need to search users by various fields such as username, email address, first name, and last name. Is there a way to perform a search that will return all users who match any of these fields? For example, if I search for “john”, I want to see all users whose username, email address, first name, or last name contain the string “john”. Is there a function or method in WordPress that allows me to do this type of search, and if so, can you provide an example of how to use it?

You can use both the WP_User_Query class and the get_users() function. You need to specify the criteria for the search, such as the field(s) to search and the value(s) to search for as arguments. Here’s an example of how you could use WP_User_Query to search for users.

$search_query = 'john'; 

$user_query = new WP_User_Query( array(
    'search'         => '*' . $search_query . '*',
    'search_columns' => array(
        'user_login',
        'user_email',
        'display_name',
        'first_name',
        'last_name'
    )
) );

$users = $user_query->get_results(); // Get the search results

Alternatively

$search_query = 'john'; 

$users = get_users( array(
    'search'         => '*' . $search_query . '*',
    'search_columns' => array(
        'user_login',
        'user_email',
        'display_name',
        'first_name',
        'last_name'
    )
) );