Get user role by using user_id in buddypress

I need to classify the user according to their role, so I need to find the user role by using the user_id alone (not only for logged in users but for all the BP users).

Something like this $user_role=role($user_id);

2 Answers
2

Try this function:

function get_user_role($user_id){
    global $wpdb;
    $user = get_userdata( $user_id );
    $capabilities = $user->{$wpdb->prefix . 'capabilities'};
    if ( !isset( $wp_roles ) ){
        $wp_roles = new WP_Roles();
    }
    foreach ( $wp_roles->role_names as $role => $name ) {
        if ( array_key_exists( $role, $capabilities ) ) {
            return $role;
        }
    }
    return false;
}

I’ve not included any exception handling like whether the user exist or not, so you can do it yourself or in case you are getting the user ids list wont even be necessary.

Leave a Comment