Wordpress: get current user role

Viewed 8322

I have this function to add the current user role as a class in the body.

add_filter( 'body_class', 'custom_class' );
function custom_class( $classes ) {
        $classes[] = get_user_role();

    return $classes;
}

It doesn't work and I know that the problem is get_user_role() in this line:

 $classes[] = get_user_role();

What's wrong in this line?

If I use this line instead, it works fine:

 $classes[] = "someText";
4 Answers

i cant find get_user_role() function in wordpress

I think you are looking for

$current_user = wp_get_current_user();

and you can point out the the display name of that user as

$current_user->display_name

and in body class function

add_filter( 'body_class', 'custom_class' );
function custom_class( $classes ) {
    $classes[] = $current_user->display_name;

return $classes;
}

This is what i use:

function my_body_classes( $classes ) {
global $current_user;
$classes[] = array_shift($current_user->roles);
}
add_filter('body_class', 'my_body_classes');

Works Great!

you can try to use this code

  function custom_class($classes) {  
     global $current_user; 
     $user_role = array_shift($current_user->roles);  
     $classes[] = $user_role; 
     return $classes;
    }
  add_filter('body_class','custom_class');
Related