'How to customize WordPress admin panel menu access for specific user

I have a contributor role which cap is below:

WP_Role Object
(
    [name] => contributor
    [capabilities] => Array
        (
            [edit_posts] => 1
            [read] => 1
        )

)

This role can see this screen on the admin panel:

enter image description here

Now, I want to remove all the access of these menu items except Dashboard and want to give him a custom post type access (Trainer).

Basically, I am trying to customize the WordPress admin panel for a new user role who can see/add/edit/delete his dashboard + some custom posts.

Could you pleae tell me how can I do this?



Solution 1:[1]

You would use remove_admin_page(). If you need to remove a submenu, then you would use remove_submenu_page(). First we get the current user amd their roles.

function namespace_hide_menu_pages() {
    $user = get_current_user();
    $user_role = $user->roles;
    
    if ( $user && is_user_logged_in() && 'role-slug' == $user_role ) {
       remove_admin_page( 'menu_page_slug' );
    }
}
add_action( 'admin_head', 'namespace_hide_menu_pages' );

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JayDev95