最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

grant multiple roles access to specific admin menu item

programmeradmin4浏览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!

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!

Share Improve this question asked Apr 11, 2020 at 13:25 YatoYato 175 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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.

发布评论

评论列表(0)

  1. 暂无评论