Wordpress:检查前端的自定义用户角色
Wordpress: check for custom user role in frontend
我只是想在用户具有 自定义 用户角色时显示一些消息。它适用于本机用户角色,但不适用于自定义用户角色。这是我的代码:
<?php
$user_ID = get_current_user_ID();
$user = new WP_User( $user_ID );
$current_user = $user->roles[0];
if( $current_user == 'client' ){
echo 'hello client';
} else {
// do nothing
}
?>
欢迎任何帮助,谢谢!
你可以试试这个:
if ( is_user_logged_in() )
{
global $current_user;
$user_role = $current_user->roles[0];
if($user_role == 'client')
{
// do something
}
}
is_user_logged_in()
用于检查用户是否登录
如果用户设置了多个角色,上述示例就会出现问题,因为代码只检查用户设置的第一个角色。
理想情况下,您应该检查是否有任何用户角色与自定义角色匹配:
if ( is_user_logged_in() ) {
global $current_user;
if( in_array('YOUR_CUSTOM_ROLE', $current_user->roles) ) {
echo 'User has Custom Role';
} else {
echo 'User does not have Custom Role';
}
}
我只是想在用户具有 自定义 用户角色时显示一些消息。它适用于本机用户角色,但不适用于自定义用户角色。这是我的代码:
<?php
$user_ID = get_current_user_ID();
$user = new WP_User( $user_ID );
$current_user = $user->roles[0];
if( $current_user == 'client' ){
echo 'hello client';
} else {
// do nothing
}
?>
欢迎任何帮助,谢谢!
你可以试试这个:
if ( is_user_logged_in() )
{
global $current_user;
$user_role = $current_user->roles[0];
if($user_role == 'client')
{
// do something
}
}
is_user_logged_in()
用于检查用户是否登录
如果用户设置了多个角色,上述示例就会出现问题,因为代码只检查用户设置的第一个角色。
理想情况下,您应该检查是否有任何用户角色与自定义角色匹配:
if ( is_user_logged_in() ) {
global $current_user;
if( in_array('YOUR_CUSTOM_ROLE', $current_user->roles) ) {
echo 'User has Custom Role';
} else {
echo 'User does not have Custom Role';
}
}