Wordpress - How to check if a user exists by a given id
I would highly recommend Daniel's much simpler solution over the one currently selected as correct:
$user = get_userdata( $user_id );
if ( $user === false ) {
//user id does not exist
} else {
//user id exists
}
In this case I will definetely not use the get_userdata( $user_id ) while it is returning a WP_User, so it is more greedy than just a custom query.
About the query, I agree using the prepare method, but the SELECT COUNT(*) means you are returning all columns, which is useless here.
I would recommend using SELECT COUNT(ID) unstead, in this way we are only working on a single column which will be faster.
On other aspect for the returning statement, it would be more readable with a Ternary Logic like :
return 1 < $count ? true : false;
To sum up, I wouldd have implemented it like :
function user_id_exists( $user_id ) {
global $wpdb;
$count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(ID) FROM $wpdb->users WHERE ID = %d", $user_id ) );
return empty( $count ) || 1 > $count ? false : true;
}
If performance is a concern, use:
function user_id_exists($user_id) {
global $wpdb;
// Check cache:
if (wp_cache_get($user_id, 'users')) return true;
// Check database:
if ($wpdb->get_var($wpdb->prepare("SELECT EXISTS (SELECT 1 FROM $wpdb->users WHERE ID = %d)", $user_id))) return true;
return false;
}
Otherwise, use get_userdata($user_id) !== false
. The call to get_userdata
will retrieve a whole row from the database instead of a single value, create a new WP_User object and cache it on success.