Wordpress get user role from plugin

Categorías: 

Etiquetas: 

  • Method 1: by global $current_user for the current user logged in
  • Method 2: check if an user has a specific role by SQL query

Method 1: by global $current_user for the current user logged in

/**
 * Checks if current user has administrator role
 * @return boolean
 */
function user_is_admin_example() {
    global $current_user;
 
    // check if current user is logged in
    if (is_user_logged_in()) {
        // if has administrator rol, return true
        if (in_array('administrator', $current_user->roles)) {
            return true;
        }
    }
    return false;
}

Method 2: check if an user has a specific role by SQL query

/**
 * Returns true|false if user has role
 * @param integer $ID
 * @param string $role
 * @return boolean
 */
function userHasRole($ID, $role)
{
    global $wpdb;
    $sql = "SELECT ID,display_name 
                FROM $wpdb->users u 
                    INNER JOIN $wpdb->usermeta m ON m.user_id = u.ID 
                WHERE u.ID = ".$ID." 
                   AND m.meta_key = 'wp_capabilities' 
                   AND m.meta_value LIKE '%" . $role . "%'" ;
    $result = $wpdb->get_results($sql);
    if (count($result)>0) {
        return true;
    } else {
        return false;
    }
}