Menü schliessen
Created: January 10th 2024
Last updated: March 16th 2024
Categories: Common Web Development,  Php,  Wordpress
Author: Tim Fürer

WordPress: How to hide admin pages for unprivileged users

Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

In WordPress, ensuring the security and integrity of your website is paramount. One aspect of this is controlling access to various admin pages. While WordPress provides robust user roles and capabilities, sometimes you need to hide specific admin pages from users who don't have the privilege to manage all options. In this article, we'll explore a practical approach to hide certain admin pages in WordPress for users with restricted permissions.


User Capabilities

WordPress offers several user roles such as Administrator, Editor, Author, Contributor, and Subscriber. Each role comes with predefined capabilities, allowing users to perform certain actions within the WordPress dashboard. The 'manage_options' capability, typically associated with the Administrator role, grants users the authority to access and modify all settings and options within WordPress.


Hiding Admin Pages


To hide specific admin pages for users who do not have the 'manage_options' capability, we can utilize a simple PHP function hooked into the 'admin_menu' action hook. Let's break down the example code provided:

<?php

function remove_admin_pages()
{
    if (current_user_can('manage_options')) {
        return;
    }

    remove_menu_page('edit.php');
    remove_menu_page('tools.php');
    remove_menu_page('plugins.php');
    remove_submenu_page('themes.php', 'themes.php');
}
add_action('admin_menu', 'remove_admin_pages');

?>

Explanation:

  • The 'remove_admin_pages' function is hooked into the 'admin_menu' action hook, which fires after the basic admin menu structure is in place.
  • Within the function, we use the 'current_user_can' function to check if the current user has the capability to 'manage_options'. If they do, the function returns early, allowing full access to all admin pages.
  • If the user does not have the 'manage_options' capability, the 'remove_menu_page' function is used to remove specific top-level menu pages from the admin menu. In this example, we remove 'Posts', 'Tools', and 'Plugins' pages.
  • Additionally, the 'remove_submenu_page' function is used to remove a submenu page ('Themes') associated with a top-level menu page ('Appearance').

Customization

You can customize this code snippet to suit your specific requirements. Simply replace the menu page slugs ('edit.php', 'tools.php', 'plugins.php', etc.) with the slugs of the pages you want to hide. You can find these slugs by inspecting the URLs of the admin pages.