How to add the logged-in user’s roles as classes in the body element in WordPress

coffee writing computer blogging

To add the user roles to the body of your WordPress pages, you can use the body_class hook. This hook allows you to add custom classes to the <body> element of your pages.

Example of body_class hook to add classes to the body element

Here’s an example of how you can use this hook to add the user roles to the body of your pages:

function add_user_roles_to_body_class( $classes ) {
    $current_user = wp_get_current_user();
    $user_roles = (array) $current_user->roles;
    foreach ( $user_roles as $role ) {
        $classes[] = 'role-' . $role;
    }
    return $classes;
}
add_filter( 'body_class', 'add_user_roles_to_body_class' );

This code will get the current user’s roles and add a class to the body for each role. For example, if the user has the “editor” and “author” roles, the body will have the classes role-editor and role-author.

You can then use these classes in your CSS to style different elements differently based on the user’s role.

Note: This code should be placed in your theme’s functions.php file or in a custom plugin.


Posted

in

,

by

Tags: