0

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.

2 Answers 2

0

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.

0

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.

1
  • Excelent answer and well explainded. Thanks for your feedback. Commented Dec 26, 2017 at 17:45

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.