1

I am writing a plugin and I am trying to only display the admin dashboard menu item to specific roles. I have this controlling snippet so far...

// Check User Role
 global $current_user;
  if( !empty($current_user->roles) ){
    foreach ($current_user->roles as $key => $value) {
      if( $value == 'administrator' ){
           new myplugin_Wp_List_Table();
      }
    }
  }

This isn't working for some reason, when i'm logged in as administrator it doesn't display the menu.

Anyone any ideas?

1 Answer 1

3

I think is a better strategy, that you add on the activation a new capability and add this capability to the Administrator role. This makes possible for installations with much different roles to the WP default to add this capability to other roles or for the requirement of a installation to add the view to another role.

Add Cap to a Role

add_action( 'admin_init', 'fb_add_capabilities' );
function fb_add_capabilities() {

    `$GLOBALS['wp_roles']->add_cap( 'administrator', '_your_custom_cap' );`
}

Check for Cap

Inside your source can you check for this capabilty:

if ( ! current_user_can( '_debug_objects' ) )
    return;

Remove Cap

On the deactivation (Hook register_deactivation_hook) and uninstall (Hook register_uninstall_hook) of the plugin is it necessary, that you remove the cap. remove_cap()

Example

A example in the wild can you finde in this plugin, file.

1
  • Much better way of doing it, thanks for the pointers Apr 29, 2014 at 12:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.