I have 4 different user roles in my Wordpress site + the extra administrator role.
I have a <div>
that I would only like to display to "manager" user role.
The following code should be only aimed to "manager" user role. So if the user has a "manager" user role, they will see the notice in the <p>
block that says : This is a premium feature. You must have premium capabilities to upload your banner
Else If the user "is not" a "manager", they will have an option to upload a banner.
I have this code in place :
<?
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>
It works great for all user roles including "manager", but If I see the page as an "administrator" , I see what the "manager" should see. I see the premium feature notice. But instead I should be able to upload a banner.
So what I am I doing wrong ?
If you want to check the user role(s) of the current logged in user you have to check the role on the current_user-object.
$user_roles = $current_user->roles; // Array
but it is always better to check for the user capabilities.
if you still want to check the role of a user, here is a function that i wrote, ... maybe it helps you
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");