Skip to content

Instantly share code, notes, and snippets.

@hellofromtonya
Created June 11, 2015 16:43
Show Gist options
  • Save hellofromtonya/4a7f8180726a168051af to your computer and use it in GitHub Desktop.
Save hellofromtonya/4a7f8180726a168051af to your computer and use it in GitHub Desktop.
Fetching User Meta by Role
<?php
/**
* Fetch user meta for the specified role and return user ID, first name, and last name
*
* @since 1.0.0
*
* @param string $role
* @return array
*/
function wpdc_get_user_meta_by_role( $role ) {
global $wpdb;
$role = '%\"' . $role . '\"%';
$sql_query = $wpdb->prepare(
"
SELECT um.user_id, um1.meta_value AS first_name, um2.meta_value AS last_name
FROM {$wpdb->usermeta} AS um
LEFT JOIN {$wpdb->usermeta} AS um1 ON um.user_id = um1.user_id AND um1.meta_key = 'first_name'
LEFT JOIN {$wpdb->usermeta} AS um2 ON um.user_id = um2.user_id AND um2.meta_key = 'last_name'
WHERE um.meta_key = '{$wpdb->prefix}capabilities' AND CAST(um.meta_value AS CHAR) LIKE %s
",
$role
);
return $wpdb->get_results( $sql_query );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment