如何根据特定的wordpress用户角色加载CSS类

Dav*_*Dev 3 css wordpress

我的目标是只为一个特定用户角色的类提供css样式。

本质上,我希望批发购买者登录时网站标题中的徽标能够不同,因为我们通过批发商店中的一个品牌网站出售所有产品线。

在这种情况下,用户角色将是批发客户,主题是Avada 5.4.2

https://avada.theme-fusion.com/hosting/是使用相同主题的网站的示例。我希望这样做,以便当用户登录到“批发客户”角色时,Avada Hosting徽标将被应用CSS类。

CSS将是

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

这本质上(以一种非诗意的方式)隐藏了现有徽标,并用背景图像代替了它,这就是我需要的徽标。

Xhy*_*ynk 5

您可以使用body_class过滤器将当前用户的角色添加到正文中。您可以将此代码放在主题functions.php文件中。

注意:如果您没有使用子主题,并且高级主题已更新,则可能会丢失所做的更改;否则,可能会丢失更改。在这种情况下,最好将代码放在MU-Plugin文件中,或者使用PHP插入插件。我过去有过不错的经验My Custom Functions

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;
}
Run Code Online (Sandbox Code Playgroud)

这将允许您在CSS选择器中使用它:

.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;
}
Run Code Online (Sandbox Code Playgroud)

次要功能更新:

这是为您提供的更简洁的功能,该功能还可以容纳用户很少有多个角色的情况:

add_filter( 'body_class', function( $classes ){
    foreach( (array) wp_get_current_user()->roles as $role ){
        $classes[] = "user-role-$role";
    }
    return $classes;
});
Run Code Online (Sandbox Code Playgroud)