Search code examples
wordpresspluginsdashboard

Wordpress Plugin | New Menu Page visible for new user role but not for WP-Administrator


I am creating a new wordpress plugin. For this plugin I have created a new role named mypluginadmin. The Plugin has a "new admin menu" page which is created with function

add_menu_page( string $page_title, string $menu_title, string $capability, string $menu_slug, callable $function = '', string $icon_url = '', int $position = null )

My problem is that by default a user can only have one role assigned. When I have a user with this new role he can see the new page. A user with the default administrator role can not see the new page but of cause he should.

What can I do that this new page is also visible for users with administrator role?

The parameter $capability of function add_menu_page is not an array where I could transmit more than one value.

Can anyone please help me?

Many thanks


Solution

  • You must define ( add ) same capability for administrator and mypluginadmin roles and call that as value of $capability in add_menu_page function.

    For example)

    First add same capability with custom name for example "access_custom_admin_menu" to both user roles

    // get the the role object
    $admin_role = get_role( 'administrator' );
    // grant the access_admin_custom_menu capability
    $admin_role->add_cap( 'access_custom_admin_menu', true );
    
    // get the the role object
    $mypluginadmin_role = get_role( 'mypluginadmin' );
    // grant the access_admin_custom_menu capability
    $mypluginadmin_role ->add_cap( 'access_custom_admin_menu', true );
    

    Then use that in function

    add_menu_page( 'your_page_title', 'your_menu_title', 'access_custom_admin_menu', 'your_menu_slug', .... 
    

    In fact, the goal is to use a capability that only these two roles have and the other user roles do not have this capability , If you currently have the capability with this feature, you do not need to do the above and just use it