wordpress: add user role on body class

php, wordpress

Solution

You can change your function to this

function get_user_role() {
    global $current_user;
    $user_roles = $current_user->roles;
    $user_role = array_shift($user_roles);
    return $user_role;
}

Then, change your body tag like this

<body <?php body_class( get_user_role() ); ?>>

If the user isn't logged in, it will not add anything.

Or you can also add one more function (from the codex)

add_filter('body_class','my_class_names');
function my_class_names($classes) {
    $classes[] = get_user_role();
    return $classes;
}

That will work.

Problem

I'm trying to add the user role once a user is logged in on wordpress and have the user role be in the body class="" ``` function my_class_names($classes) { global $current_user; $user_roles = $current_user->roles; $user_role = array_shift($user_roles); if ( is_user_logged_in() ) { $classes[] = $user_role; } return $classes; } add_filter('body_class','my_class_names'); ``` I'm not a php guy already tried research and i found how to get the user role, and another post was how to add body class and i'm have trouble how to get them both to work. I hope someone can help me out with this spent more than 2hrs trying to figure this out by myself :(

Original source