The get_user_by
function is a WordPress function that is used to retrieve a user object by searching for a specific value in a specified field. This function is commonly used in WordPress development when working with user authentication or when retrieving user information.
The function requires two parameters: $field
and $value
. The $field
parameter specifies which field to search for the value in, and the $value
parameter is the value being searched for. The function returns a WP_User object if a user is found, or null if no user is found.
Here is an example usage code:
$user = get_user_by( 'email', 'user@example.com' );
if ( $user ) {
echo 'User ID is: ' . $user->ID;
}
In this example, we are searching for a user by their email address. If a user with the email address user@example.com
is found, their user ID will be echoed to the page.
Another possible usage of the function could be to search for a user by their username, like this:
$user = get_user_by( 'login', 'john_doe' );
if ( $user ) {
echo 'User email is: ' . $user->user_email;
}
In this case, we are searching for a user with the username john_doe
. If a user is found, their email address will be echoed to the page.