0

I am writing a plugin that offers an admin menu item which only a specific, custom user role ("customrole" in the example) can access. I have implemented this as follows, and it works:

function add_admin_menu() {
add_menu_page(
    'Custom-Plugin',
    'Custom-Plugin',
    'customrole',
    'custom-plugin',
    'init_custom_menu_page'
    );
}

The problem is that the administrator does not have the rights to access this menu item anymore; I would like administrators to still be able to access it, however (and the "customrole"-users). How can I achieve this?

I am using the "Members" plugin to create custom user roles if that makes a difference.

Thanks in advance!

1 Answer 1

0

You shouldn't use Roles to handle permissions for your menu page. Instead, use capabilities, and then assign those capabilities to whichever roles should have access.

For example, instead of creating a customrole role, use a custom capability like manage_custom_plugin:

add_menu_page(
    'Custom-Plugin',
    'Custom-Plugin',
    'manage_custom_plugin',
    'custom-plugin',
    'init_custom_menu_page'
);

Now, using the Members plugin you can enter manage_custom_plugin into the "Custom Capability" box, and add it to whichever roles you need.

In code you would grant this capability to roles using WP_Roles::add_cap(), like so:

$roles = wp_roles();

$roles->add_cap( 'administrator', 'manage_custom_plugin' );
$roles->add_cap( 'editor', 'manage_custom_plugin' );

Just be aware that these functions write to the database, so should only be run once, on plugin or theme activation.

1
  • I see, thank you very much!
    – Yato
    Commented Apr 14, 2020 at 8:32

Your Answer

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

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