I am developing a plugin for wordpress, I want to find if current user is administrator or not, unfortunately I could not use the current_user_can() as it gives me error, so am using the global $current_user. But I could not get inside the if part even for admin user.. How to fix this?
global $current_user;
if ($current_user->role[0]=='administrator'){
function hide_post_page_options() {
//global $post;
// Set the display css property to none for add category and add tag functions
$hide_post_options = "<style type=\"text/css\"> .jaxtag { display: none; } #category-adder { display: none; } </style>";
print($hide_post_options);
}
add_action( 'admin_head', 'hide_post_page_options' );
}
First off, we check that the user is actually logged in. If they're not logged in, they won't have a role assigned. If the user is logged in, we use wp_get_current_user to return the WP_User object. This provides us with a stack of information about the data and we can access their user role(s) via $user->roles .
On a regular WordPress website, the administrator role is the most powerful user role. Users with the administrator role can add new posts, edit posts by any users, and delete those posts. Plus, they can install, edit, and delete plugins and themes.
The six default WordPress user roles. Out of the box, WordPress includes six different user roles. Understanding each one is key if you want to protect your site and ensure your team works more effectively. Let's take a look at each of these roles in turn.
Find User ID in WordPress Dashboard This is by far the most simple way to get a WordPress user's ID. First, you'll need to login to your WordPress admin dashboard. From here you can select the user you want the ID of by clicking edit. This will lead you to the user edit page.
Try something like the following:
if ( current_user_can( 'manage_options' ) ) { /* A user with admin privileges */ } else { /* A user without admin privileges */ }
Read more about the current_user_can
function here.
Get the user and check if it has the role adminstrator, like so:
function is_site_admin(){
return in_array('administrator', wp_get_current_user()->roles);
}
if (is_site_admin()) {
echo 'Woot Woot';
} else {
echo 'So sad, I have no rights';
}
This works for me:
global $current_user;
if( !empty($current_user->roles) ){
foreach ($current_user->roles as $key => $value) {
if( $value == 'administrator' ){
Do Something
}
}
}
If it's not a multi-site set-up, you can use this to detect an administrator. If it's multi-site, this will only return true for a super admin.
$user_ID = get_current_user_id();
if($user_ID && is_super_admin( $user_id )) {
Do Something
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With