Hide top admin panel for non admin and non editors

So i came to three posible solutions to this question and can't decide which is better. What is your opinion?

First solution:

if ( ( in_array('administrator', userdata('role')) || in_array('editor', 
userdata('role')) ) == false)
{   
add_filter('show_admin_bar', '__return_false');
}

Second one:

if( ( current_user_can('editor') || current_user_can('administrator') ) == false )
{
add_filter('show_admin_bar', '__return_false');
}

Third one:

$allowed_roles = array('editor', 'administrator');
if( array_intersect($allowed_roles, userdata('role') ) == false ) {
add_filter('show_admin_bar', '__return_false');
} 

User data function:

function userdata($userdata){
$userinfo = wp_get_current_user();
if ($userdata == 'nick')
return $userinfo -user_login;
if ($userdata == 'mail')
return $userinfo -user_email;
if ($userdata == 'id')
return $userinfo -ID;
if ($userdata == 'role')
return $userinfo -roles;
else
return 'Eror';
}

I am voting for the third solution.

Topic content-restriction privileges user-roles admin users Wordpress

Category Web


The first method is inefficient as it runs the userdata function twice, but that is easily fixed:

$roles = userdata('role');
if ( ( in_array('administrator', $roles) || in_array('editor', $roles) ) == false )
{   
    add_filter('show_admin_bar', '__return_false');
}

However the third method does essentially the same thing in a better way.

The second method uses current_user_can, which is unreliable when used to check roles, as per the documentation.

However, if you are certain of the capabilities different roles will have now or in future, you could do something like this:

if( !current_user_can('edit_others_posts') )
{
    add_filter('show_admin_bar', '__return_false');
}

By default only admins and editors have this capability, so checking for this tells you what you need to know, if the default is certain to be used.


This is what i am using;

add_action('init', 'blockusers_init');

function blockusers_init() {
    if (is_admin() && !current_user_can('administrator') &&
        !(defined('DOING_AJAX') && DOING_AJAX)) {
        wp_redirect(home_url());
        exit;
    }
}

It's possible the best one.

EDIT : You need a custom login page for reach wp-admin. This code redirect to homepage if you enter directly to wp-admin.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.