WordPress Menu with logo
WordPress Snippets

Hide a WordPress Admin Menu Based on User Role

Sometimes there may be areas of the WordPress admin area that you do not want your users to have access to. For example, you may want editors to be able to edit the content of pages but not be able to add posts. There may be a custom post type that you have added that you do not want some users to have access to. It is fairly simple to add a snippet of code to your theme’s functions.php file that will check a user’s role or capabilities and remove menu items accordingly.

Remove Admin Menu based on User Role.

  • First you need to decide which user role you want to have access to the particular menu. In this example the WordPress Download Manager plugin has been installed and only Administrators should have access to the menu to add new downloads.
  • Secondly you need to find the link for the menu to add it to the remove part. You can find the menu link for any of the menu items in the left menu bar by hovering the mouse over them and checking the link in the browser. You are looking for the information after the ‘edit.php?’ part of the url. E.g. if you want to hide the Pages menu the full url will be similar to: ‘mywebsite.com/wp-admin/edit.php?post_type=page’ the part you need to know is ‘post_type=page’.

Once you have the above information you can create an action hook to amend the menu based on the user role. Take a look at the WordPress Codex to find other ways to check for roles or capabilites. This page also has useful information about Roles and Capabilities if you are building a plugin or theme.

The Code

First create the action hook and assign it a custom function. (Line 3)

Then write the function. Call the global variable for the user role. The If statement is checking whether the user is NOT an administrator, the exclamation mark is indicating the negative: Not. If the user is an admin the menu should display, for all other roles, (i.e. if the user is not an admin), the menu item should be removed. The menu that is being removed on Line 9 is the Download Manager custom post type menu. You can replace this with the menu you want to remove, e.g. post_type=page to remove the pages menu.

Once the above code is placed in the theme’s functions.php file, the menu will disappear from the Dashboard of all users who aren’t an administrator.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.