Check if User Exists by ID in WordPress

August 26, 2016

WordPress has a built in username_exists() function to check if a user exists by their username, but there isn’t a similar function for checking if a user exists by their user ID. I’ve seen posts online where folks suggest a way of doing that with a direct database query using $wpdb. While that works, the function below is a bit cleaner and uses a native WordPress function to accomplish the same thing.

You can pass either a user ID or a WP_User object to this function and it will return true if that user exists or false if not.

<?php
/**
* Does this user exist?
*
* @param int|string|WP_User $user_id User ID or object.
* @return bool Whether the user exists.
*/
function km_does_user_exist( $user_id = '' ) {
if ( $user_id instanceof WP_User ) {
$user_id = $user_id->ID;
}
return (bool) get_user_by( 'id', $user_id );
}


Kellen Mace

Written by Kellen Mace, who lives in Rochester Hills, MI and builds cool stuff on the web. About Kellen // Follow him on Twitter →