【问题标题】:If / Else statement - not working for admin role - wordpressIf / Else 语句 - 不适用于管理员角色 - wordpress
【发布时间】:2015-02-24 14:59:07
【问题描述】:

我的 Wordpress 网站中有 4 个不同的用户角色 + 额外的管理员角色。

我有一个 <div>,我只想显示给“经理”用户角色。

以下代码应仅针对“经理”用户角色。因此,如果用户具有“经理”用户角色,他们将在<p> 块中看到通知:这是一项高级功能。您必须具备高级功能才能上传您的横幅

其他 如果用户“不是”“经理”,他们将可以选择上传横幅。

我有这段代码:

<?
if(current_user_can('manager')) { ?>    
    <div class="button-area">
        <i class="fa fa-cloud-upload"></i>
        <p class="banner-help-block-heading">UPLOAD BANNER</p>
        <p class="banner-help-block">This is a premium feature. You must have premium capabilities to upload your banner</p>
        <div class="upgrade-button">
            <a href="#" class="button-green-upgrade">Upgrade Account</a>
        </div>
    </div><?
        $manager = true;
    }
else { ?>
    <div class="button-area<?php echo ($banner)? ' elect-hide':''; ?>">
        <i class="fa fa-cloud-upload"></i>
        <a href="#" class="elect-banner-drag elect-btn elect-btn-info"><?php _e('Upload banner', 'elect'); ?></a>
        <p class="help-block"><?php _e('Upload a banner for your profile. Banner size is (825x300) pixel.', 'elect'); ?></p>
    </div><?php 
    $manager = false;
    } ?>

            </div>  

它适用于所有用户角色,包括“经理”,但如果我将页面视为“管理员”,我会看到“经理”应该看到的内容。我看到了高级功能通知。但我应该可以上传横幅。

那么我做错了什么?

【问题讨论】:

  • 我在codex.wordpress.org/Function_Reference/current_user_can 上没有看到manager 参数
  • 那是一个用户角色,它可以是任何东西......它可以是“音乐家”
  • “WordPress 有六个预定义的角色:超级管理员、管理员、编辑、作者、贡献者和订阅者”codex.wordpress.org/Roles_and_Capabilities 我错过了什么,或者您正在使用一些自定义角色?
  • 是的,除了这些预定义的角色之外,您还可以创建适合您正在创建的网站的利基市场的其他角色.. 如果您愿意,可以是音乐家、鼓手或吉他手.. 如果您正在使用 Woocommerce 并销售产品,那么您可以担任“卖家”角色..如果您有会计业务,您可以添加“经理”或“会计师”角色..
  • 很高兴知道,你说上面的代码有效,那么在条件if(current_user_can('manager') || current_user_can('manage_options'))添加管理员怎么样?

标签: php wordpress


【解决方案1】:

如果您想检查当前登录用户的用户角色,您必须检查 current_user-object 上的角色。

$user_roles = $current_user->roles; // Array

但最好检查一下用户的能力。

如果你仍然想检查用户的角色,这是我写的一个函数,...也许它可以帮助你

function mi_checkUserRole($role, $userid = null) {
    $user = null;
    if ( !empty($userid) ) {
        $user = new WP_User( $userid );
    } else {
        global $current_user;
        get_currentuserinfo();
        $user = $current_user;
    }
    if ( !empty($user) ) {
        return in_array($role, $user->roles);
    }
    return false;
}

// Example:
$isManager = mi_checkUserRole("manager");

【讨论】:

  • 将函数添加到主题的functions.php中。然后您可以通过调用函数来检查用户角色(如函数代码下方的示例中)。
猜你喜欢
  • 2019-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-02
  • 1970-01-01
  • 2021-08-26
相关资源
最近更新 更多