Slushman

unsplash-logo david pl

Find User ID by User MetaData

Published 2011-07-25

I just wrote this useful function and thought I’d share. I’m working on a plugin for my employer, Belmont University. I needed to find a user’s ID by the user’s barcode metadata. WordPress does not have a built-in function for this, but this custom function works nicely. Add it to your theme’s functions.php file or to a plugin file (in my case, this is part of plugin). Here’s the function:

/**
 * Returns a list of user IDs matching the metavalue
 * @param 	string 		$metakey 	The metadata key
 * @param 	string 		$metavalue 	The value to find
 * @return	array|bool 			An array of user IDs or false
 */
function get_user_by_metadata($metakey, $metavalue) {
    $return = [];

    $args['fields'] = 'ID';
    $args['meta_key'] = $metakey;
    $args['meta_value'] = $metavalue;

    $user_query = new WP_User_Query($args);

    if (empty($user_query->results)) { return FALSE; }

    return $user_query;
} // get_user_by_metadata()

Gist of the code above

Keep in mind, this returns an array, not a string.

Share this post!

Check out these most recent posts:

How to Add a Class to a Metabox

Toggling the visibility of a metabox using a form requires the metabox to have a custom class. This is how to add custom classes to a metabox.

ArtistDataPress Expiration

In case you haven’t heard, ArtistData is shutting down, so the ArtistDataPress plugin will also be shutting down as of October 14.

Avoiding get_theme_mod Errors

If you’re getting an error related to the get_theme_mod function, the solution is simpler than you think. Check out this solution.