Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a CSS class based on specific wordpress user role

Tags:

css

wordpress

My goal is to give css styling to a class for only one specific user role.

Essentially I want the logo in the header of my site to be different when a wholesale buyer logs in since we sell all of our lines through one of our brand sites in a wholesale store.

In this case the user role would be Wholesale Customer and the theme is Avada 5.4.2

https://avada.theme-fusion.com/hosting/ is an example of a site using the same theme. I would like it so that when a user is logged in to the Wholesale Customer role the Avada Hosting logo would have a CSS class applied to it.

The CSS would be

img.fusion-standard-logo {
  box-sizing: border-box;
  background: url(http://notrealdomain2.com/newlogo.png) no-repeat;
  width: 165px; 
  height: 70px; 
  padding-left: 180px;
}

This essentially (in a very non poetic way) hides the existing logo and replaces it with a background image which would be the logo I need.

like image 453
DaveDoesDev Avatar asked Jan 02 '23 14:01

DaveDoesDev


1 Answers

You could add the current user's role to the body using the body_class filter. You can put this code in your theme's functions.php file.

Note: If you're not using a child theme, and your premium theme updates, you may lose the changes you made; in which case putting the code in a MU-Plugin file, or using a PHP insertion plugin would be a better bet. I've had a decent experience with the My Custom Functions in the past.

add_filter( 'body_class', 'add_role_to_body_class' );
function add_role_to_body_class( $classes ) {
    $current_user = wp_get_current_user();
    $current_role = (array) $current_user->roles;

    if( $current_role[0] ){
        $classes[] = 'user-role-'.$current_role[0];
    }

    return $classes;
}

This would allow you to use that in your css selector:

.fusion-standard-logo {
    box-sizing: border-box;
    background: url(http://example.com/logo.png) no-repeat;
    width: 165px; 
    height: 70px; 
    padding-left: 180px;
}

.user-role-author .fusion-standard-logo {
    background: url(http://example.com/logo-for-authors.png) no-repeat;
}

.user-role-wholesale_customer .fusion-standard-logo {
    background: url(http://example.com/logo-for-wholesale_customers.png) no-repeat;
}

Minor Function Update:

Here's a more succinct function for you, that will also accommodate the rare case of multiple roles on a user:

add_filter( 'body_class', function( $classes ){
    foreach( (array) wp_get_current_user()->roles as $role ){
        $classes[] = "user-role-$role";
    }
    return $classes;
});
like image 101
Xhynk Avatar answered Jan 13 '23 14:01

Xhynk