How to Hide Posts and Pages from Users within the WordPress Admin

Home » Snippets » How to Hide Posts and Pages from Users within the WordPress Admin
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

When building a WordPress site with multiple users, you may want to hide certain posts and pages from certain users or user roles. This can be helpful for keeping sensitive information hidden or for simplifying the editing experience for different users. In this article, we’ll show you how to easily hide posts and pages from certain users or roles using a simple code snippet. Let’s dive into it.

					function wpturbo_hide_posts_from_users() {
    if ( ! current_user_can( 'manage_options' ) ) {
        // hides posts and pages from non-admin users
        remove_menu_page( 'edit.php' );
        remove_menu_page( 'edit.php?post_type=page' );
    }
}
add_action( 'admin_menu', 'wpturbo_hide_posts_from_users' );
				

The wpturbo_hide_posts_from_users() function is triggered by the admin_menu action in WordPress. With this function, we can remove menu pages that display posts and pages within the WordPress administration panel for users who do not have the ‘manage_options’ capability. This capability is only available to administrators, so this code will essentially hide posts and pages from non-admin users.

To achieve this, we first determine if the current user has the manage_options capability using the current_user_can() function. If the user does not have this capability, we will remove the menu pages that display posts and pages in the WordPress admin panel using the remove_menu_page() function. The 'edit.php' and 'edit.php?post_type=page' are the menu slugs for posts and pages, respectively.

Finally, we attach the wpturbo_hide_posts_from_users() function to the admin_menu action using the add_action() function. This ensures that the function is called when the WordPress admin menu is being generated, and that the user capability check and menu removal code is executed at the right time.

This code is useful for developers who want to limit the access of certain users, such as editors or contributors, to the posts and pages in WordPress. By hiding these pages in the admin panel, you can help ensure that only the right users are able to edit and publish content.

Register an account to save your snippets or go Pro to get more features.