JPashs
JPashs

Reputation: 13886

Wordpress: get current user role

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";

Upvotes: 5

Views: 11260

Answers (4)

mondi
mondi

Reputation: 559

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!

Upvotes: 0

realmag777
realmag777

Reputation: 2088

Please try the code below:

function get_current_user_role() {
   if(is_user_logged_in()) {
       $user = wp_get_current_user();
       $role = (array) $user->roles;
       return $role[0];
   } 
   else {
     return false;
   }
}

Upvotes: 3

Shubham Saini
Shubham Saini

Reputation: 182

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');

Upvotes: -1

sagar
sagar

Reputation: 590

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;
}

Upvotes: 1

Related Questions