WordPress offers a number of options to obtain the user ID. There are various options depending on the situation. There are 3 types of situations:
- A list of users
- The current logged-in user
- A specific user
A list of users
When iterating over a list of users it is pretty simple to obtain the ID of each user because the get_users()
function returns objects including all user data.
$users = get_users( $args );
foreach ( $users as $user ) {
echo $user->ID;
}
The current logged-in user
To obtain the user ID of the current logged in user I use the following code:
$user_id = get_current_user_id();
A specific user
To obtain the user ID of a specific user we need some other user data of the user. For example an e-mail address or login name.
$user = get_user_by( 'email', 'user@example.com' );
$user_id = $user->ID;