WordPress检查用户角色功能(多个角色)?

时间:2013-05-16 作者:Syrehn

我在玩弄check_user_role function 按AppThemes组合;如WordPress current\\u user\\u can codex页面所述。在AppThemes教程代码中,它引用了以下内容:

// example use for the current user
if ( appthemes_check_user_role( \'customer\' )
    _e( "You\'ve got access dude!", \'appthemes\' );
else
    _e( "Sorry man, no luck.", \'appthemes\' );
我想让它与一个以上的用户角色(即“customrole”、“subscriber”)一起工作,但如果不创建感觉像是重复代码的代码,就没有太多的运气。

我让它发挥作用的唯一方法是做以下事情:

if (appthemes_check_user_role( \'customrole\' ) || appthemes_check_user_role( \'author\' ) ) {
    _e( "You\'ve got access dude!", \'appthemes\' );
} else {
    _e( "Sorry man, no luck.", \'appthemes\' );
}
或者这个:

if (appthemes_check_user_role( \'customrole\' ) ) {
    _e( "You\'ve got access dude!", \'appthemes\' );
} if (appthemes_check_user_role( \'author\' )) {
    _e( "You\'ve got access dude!", \'appthemes\' );
}else{
    _e( "Sorry man, no luck.", \'appthemes\' );
}
我想知道是否有人对简化代码以用于多个角色有什么建议?

1 个回复
SO网友:Charles Clarkson
if ( wpse_99666_check_user_roles( array( \'customrole\', \'author\' ) ) )
    _e( "You\'ve got access dude!", \'appthemes\' );
else
    _e( \'Sorry man, no luck.\', \'appthemes\' );


/**
 * Checks if a particular user has one or more roles.
 *
 * Returns true on first matching role. Returns false if no roles match.
 *
 * @uses get_userdata()
 * @uses wp_get_current_user()
 *
 * @param array|string $roles Role name (or array of names).
 * @param int $user_id (Optional) The ID of a user. Defaults to the current user.
 * @return bool
 */
function wpse_99666_check_user_roles( $roles, $user_id = null ) {

    if ( is_numeric( $user_id ) )
        $user = get_userdata( $user_id );
    else
        $user = wp_get_current_user();

    if ( empty( $user ) )
        return false;

    $user_roles = (array) $user->roles;

    foreach ( (array) $roles as $role ) {
        if ( in_array( $role, $user_roles ) )
            return true;
    }

    return false;
}
结束