get user role in wordpress code example

Example 1: how to get all roles in wordpress

/* get all role in wordpress in associative key = role(slug) => value(Role Display name) by [email protected]  */
function get_role_names() {

global $wp_roles;

if ( ! isset( $wp_roles ) )
    $wp_roles = new WP_Roles();

return $wp_roles->get_names();
}

Example 2: from user id to user role wordpress

$user_meta = get_userdata( $user_id );

$user_roles = $user_meta->roles; // array with all the roles the user is part of.

Example 3: wordpress get current user role

$user = wp_get_current_user();
if ( in_array( 'author', (array) $user->roles ) ) {
    //The user has the "author" role
}

Example 4: wordpress get wp roles

function get_role_names() {

global $wp_roles;

if ( ! isset( $wp_roles ) )
    $wp_roles = new WP_Roles();

return $wp_roles->get_names();
}

Tags:

Misc Example