WordPress: How to get role name of a user by id

September 13, 2010 | In: Wordpress

<?php
// Here we assume the $user_id store the id of requested user id.
	$user = get_userdata( $user_id );
// below line get the all capabilities from capability table.
	$capabilities = $user->{$wpdb->prefix . 'capabilities'};
        if (count($capabilities) > 0) :
	    if ( !isset( $wp_roles ) )
	   	    $wp_roles = new WP_Roles();
 
	    foreach ( $wp_roles->role_names as $role => $name ) :
		    if ( array_key_exists( $role, $capabilities ) )
			    echo $role;
	    endforeach;
        endif;
?>

This code will print the role name of the user whose id is store in $user_id variable.