WordPress: How do I remove admin menu items in wordpress
I came across a project where i was asked that the contributors and authors in WordPress see only some admin menus and not all. So I did a quick Google, and none of the solutions online gave me what I was looking for. So I just had to scribble something on my own, which gave me what I was looking for and covered what the solutions online did not!
Almost all the solutions online went to enlist what they didn’t want, and hide according to the list they prepared. I on the other hand was more into making a list of what i want them to see, and how pages likewise.
Objective: Contributors and authors in WordPress should only see Add Posts and Profile page (period).
So here goes my solution:
function msolution_remove_menus () {
global $menu, $submenu;
// current user is an Editor, do nothing/ return //
if (current_user_can('level_5'))
return;
// define main menus & sub-menus allowed //
// <strong>No we dont want him seeing the Dashboard either</strong> //
$allowed_menu = array('edit.php', 'profile.php');
$allowed_smenu = array('post-new.php', 'profile.php');
end ($menu);
while (prev($menu)){
if(!in_array($menu[key($menu)][2], $allowed_menu)) {
unset($menu[key($menu)]);
}
}
end ($menu);
while (prev($menu)){
$menu_item = $menu[key($menu)];
$submenu_item = $submenu[$menu_item[2]];
if($submenu_item != NULL && !empty($submenu_item)){
if(is_array($submenu_item)){
foreach($submenu_item as $id => $smenu){
if(!in_array($smenu[2] , $allowed_smenu))
unset($submenu[$menu_item[2]][$id]);
}
}
else
{
if(!in_array($submenu_item , $allowed_smenu))
unset($submenu[$menu_item[2]]);
}
}
}
// see if the requested page is allowed or not. //
$page_ok = false;
foreach($allowed_smenu as $smenu)
{
$result = stripos($_SERVER['REQUEST_URI'], '/'.$smenu);
if ($result!==false)
$page_ok = true;
}
// if not, send him to the profile page //
if($page_ok == false)
wp_redirect(get_option('siteurl') . '/wp-admin/profile.php');
}
add_action('admin_menu' , 'msolution_remove_menus');
thats it! Have Fun
Follow me
Tags: admin menu, codex, extend, hacks, Wordpress, wordpress.org
