Restrict Access in Admin Panel

I want to restrict access to certain plugin pages / normal WP Pages. I’ve found a way to Hide these pages from the menu but currently not restrict them. For instance, I have an editor and I don’t want them to have access to Media and Tools – I can hide those pages via this:

function editor_menu() {
    global $menu;

    if(!current_user_can('administrator'))
    {
        $restricted = array(__('Media'),__('Tools'));
        end ($menu);
        while (prev($menu)){
            $value = explode(' ',$menu[key($menu)][0]);
            if(in_array($value[0] != NULL?$value[0]:"" , $restricted)){unset($menu[key($menu)]);}
        }
    }
}
add_action('admin_menu', 'editor_menu', 999);

But how can I restrict them from viewing this page entirely? Like permissions?

Related posts

2 comments

  1. I believe the correct solution here is to just update the $capability component of the admin_menu items rather than just remove them from the menu structure.

    Try this:

    /** Set 'administrator' cap for particular menu items **/
    function update_admin_menu() {
        global $menu, $submenu;
    
        $menu[10][1] = 'administrator'; // Media
        foreach( $submenu['upload.php'] as &$item ) {
            $item[1] = 'administrator';
        }
    
        $menu[75][1] = 'administrator'; // Tools
        foreach( $submenu['tools.php'] as &$item ) {
            $item[1] = 'administrator';
        }    
    }
    add_action( 'admin_menu', 'update_admin_menu', 1000 );
    

    Please note that checking against user levels is deprecated, but it works in this situation and is essentially the same as it would be if you created a new cap (which administrators would automatically have access to,) and assigning that capability to these menu items instead.

  2. Best bet is to use a plugin such as User Roles Pro which does what you need, you can create new user roles and then restrict them from doing xx tasks in the admin.

Comments are closed.