Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 2 down vote accepted

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.

share|improve this answer
    
Much better way of doing it, thanks for the pointers –  fightstarr20 Apr 29 at 12:37

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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