【问题标题】:Wordpress capabilities and current_user_can() in functions.phpfunctions.php 中的 Wordpress 功能和 current_user_can()
【发布时间】:2012-11-15 18:59:08
【问题描述】:

我在functions.php 中添加了一个函数,用于在用户登录后将用户重定向到posts-new.php,它可以工作。但是,我只希望在登录的用户是贡献者的情况下发生这种情况。所以我添加了以下内容:

/** Redirect after login */
    function mysite_login_redirect(){
        if ( current_user_can( 'manage_options' ) ) {
           return 'http://mysite.com/wp-admin/index.php';}
        else {
           return 'http://mysite.com/wp-admin/post-new.php';}
    }
add_action( 'login_redirect', 'mysite_login_redirect');

在这种状态下,贡献者和管理员都被重定向到 post-new.php。为了测试它,我修改了函数,以便重定向没有该功能的用户:

if ( !current_user_can( 'ma ...

当我修改函数时,贡献者和管理员都被重定向到 index.php。

所以该功能似乎可以工作,但这对我来说意味着它没有看到管理员的“manage_options”功能。我尝试了几种管理员独有的功能,结果相同。很奇怪吧?

我应该说我正在使用用户角色编辑器插件,但我禁用了它并以相同的结果测试了这些功能。

我还在使用 Active Directory 集成和管理菜单编辑器。

【问题讨论】:

标签: wordpress


【解决方案1】:

试试这个:

if( current_user_can( 'administrator' ) ){} // only if administrator
if( current_user_can( 'editor' ) ){} // only if editor
if( current_user_can( 'author' ) ){} // only if author
if( current_user_can( 'contributor' ) ){} // only if contributor
if( current_user_can( 'subscriber' ) ){} // only if subscriber

或者:

if( current_user_can( 'level_10' ) ){}
if( current_user_can( 'level_9' ) ){}
if( current_user_can( 'level_8' ) ){}
if( current_user_can( 'level_7' ) ){}
if( current_user_can( 'level_6' ) ){}
if( current_user_can( 'level_5' ) ){}
if( current_user_can( 'level_4' ) ){}
if( current_user_can( 'level_3' ) ){}
if( current_user_can( 'level_2' ) ){}
if( current_user_can( 'level_1' ) ){}
if( current_user_can( 'level_0' ) ){}

【讨论】:

  • 我尝试使用 'administrator' 而不是 'manage_options' 但得到了相同的结果。如果我理解正确, current_user_can() 标记仅适用于功能而不适用于用户角色。
  • 它的参数要么是能力要么是角色名称,所以它应该可以工作(codex.wordpress.org/Function_Reference/current_user_can)。
  • 因此,无论哪种方式,该功能都不起作用,问题是该功能没有正确识别角色和功能。如果我将它设置为管理员特定角色,或者只是“管理员”,如果我以管理员身份登录,它应该使用“if”url,如果我作为贡献者登录,它应该使用“else”url。无论哪种方式,无论我将功能设置为“current_user_can”还是“!current_user_can”,管理员登录和贡献者登录的行为都与功能没有任何不同一样。
  • 从函数定义中引用:虽然部分支持检查特定角色来代替能力,但不鼓励这种做法,因为它可能会产生不可靠的结果。
【解决方案2】:

试试这个:

$exclude_role = 'contributor';
        $roles = get_role( $exclude_role )->capabilities;
        foreach ( $roles as $cap ) {
            if ( current_user_can( $cap ) ) {
                ...
            }
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-16
    • 1970-01-01
    • 2018-03-29
    • 1970-01-01
    • 2018-03-24
    • 1970-01-01
    • 2012-09-05
    • 1970-01-01
    相关资源
    最近更新 更多