The WPFolks app is out on iPhone and Android. Free, no ads. Download on the App Store Get it on Google Play
Skip to main content
Login Join
Snippet · PHP

Add a Custom Body Class Based on the Logged-in User Role

Shared by Amit Dholiya · November 3, 2026

6 views
1 upvote
Back to Snippets

Steps

  1. Add the PHP code to your theme’s functions.php file or a PHP snippets plugin.

  2. Save and activate the snippet.

  3. Log in with different WordPress user roles.

  4. Inspect the page’s HTML body class.

/**
 * Add user role as a body class
 */
function custom_add_user_role_body_class( $classes ) {

    if ( is_user_logged_in() ) {
        $user = wp_get_current_user();

        foreach ( $user->roles as $role ) {
            $classes[] = 'user-role-' . sanitize_html_class( $role );
        }
    }

    return $classes;
}

add_filter( 'body_class', 'custom_add_user_role_body_class' );

Tested on

WordPress 6.8

Reported by the author on November 3, 2026. WPFolks has not verified this.

Not tested against WordPress 7.1.4. It may still work.

Know a different way to do this? Add your approach as a variation so folks can compare them side by side.
Submit a variation

0 comments

Proudly supported by