0

I wrote a little wordpress plugin and I want to grant only specific roles or users access to it. Is there a way to do this?

2

Here how register a role specifically for a plugin and add plugin specific capabilities to selected core roles

function my_plugin_install() {
   // add a new role for plugin with some capabilities
   add_role('my_plugin_role', 'My Plugin Role', array(
     'manage_my_plugin' => true, // plugin specific capability
     'read' => true // core capability
   ));
   // add plugin capabilities for some standard roles
   $roles = array('administrator', 'editor', 'author');
   $roles_obj = new WP_Roles();
   foreach ($roles as $role_name) {
      $roles_obj->add_cap($role_name, 'manage_my_plugin' ); 
   }
}


function my_plugin_unistall() {
    remove_role( 'my_plugin_role' );
    $roles = array('administrator', 'editor', 'author');
    $roles_obj = new WP_Roles();
    foreach ($roles as $role_name) {
      $roles_obj->remove_cap($role_name, 'manage_my_plugin' ); 
    }
}

In the plugin file put:

register_activation_hook(__FILE__, 'my_plugin_install' );
register_uninstall_hook(__FILE__, 'my_plugin_unistall');

To check in the current logged user has your plugin capabilities use :

if ( current_user_can('manage_my_plugin') ) {
  // do something
}

Docs:

0
1

Are you looking for something like this?

http://wp.tutsplus.com/articles/quick-tip-user-permissions-and-your-plugin/

1
  • Thanks, this will come in handy but the problem is that custom plugins (like AllInOneSEO) are not displayed to authors in the backend. Is there a way to make them visible? – Manticore Jul 26 '13 at 11:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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