wp head – How to add css to wp_head based on user’s role?

I think this question should have an easy answer for any developer, but maybe I’m wrong.

As much as I think, I can’t understand why this snippet doesn’t work to add a css style to the head based on the role of the user visiting the site.

add_action( 'wp_head', function () {
    // Get the user object.
    $user = get_userdata( $user_id );

    // Get all the user roles for this user as an array.
    $user_roles = $user->roles;

    // Check if the specified role is present in the array.
    if ( in_array( 'customer_2', $user_roles, true ) ) { ?>


    .woofs-additional, .woofs-total {display: none!important;}

} );

It doesn’t matter what role I write, because it doesn’t work, however if I change it to
if ( ! in_array( 'customer_2', $user_roles, true ) )
CSS is always loaded regardless of user role.

Any charitable soul who can help me?

Thank you!

Leave a Comment