Sometimes it’s handy to hide pages in the WordPress admin from certain users. For example, when using WordPress as a CMS, where you define a static front page and a Posts page for all the posts, you might not want users trying to edit the Posts page since their edits won’t show up on the site anyway. A common scenario I see is users trying to edit the dummy “News” page assigned as the Posts page, or trying to change the front page of the site by editing the dummy “Home” page.
You can’t blame the users for trying to add news to their site by editing the “News” page. It makes sense. What doesn’t make sense is how WordPress does things in this regard, but that’s another discussion. To prevent this confusion, we can hide these dummy pages, or any other pages we want, from the users.
Using the code below, you can hide specific pages from all users who aren’t Administrators. It’s worth noting that this isn’t a security solution. It’s a simple piece of code for preventing confusion or accidents. If you need a real security solution, I recommend something like BU Section Editing by the fine folks at Boston University.
<?php
/*
Plugin Name: Exclude pages from admin
Plugin URI: https://www.johnparris.com/
Description: Removes pages from admin that shouldn't be edited.
Version: 1.0
Author: John Parris
Author URI: https://www.johnparris.com/
License: GPLv2
*/
function jp_exclude_pages_from_admin($query) {
if ( ! is_admin() )
return $query;
global $pagenow, $post_type;
if ( !current_user_can( 'administrator' ) && $pagenow == 'edit.php' && $post_type == 'page' )
$query->query_vars['post__not_in'] = array( '10', '167', '205' ); // Enter your page IDs here
}
add_filter( 'parse_query', 'jp_exclude_pages_from_admin' );
Someone brought up the fact that this doesn’t remove the Edit Page link from the admin bar on the front end of the site. This is true. It’s worth mentioning again that this isn’t a security solution. It’s a simple piece of code to keep people from getting confused or accidentally messing something up. Having said that, here’s a little piece of code for hiding the Edit Page link.
// Remove the Edit link from the admin bar
function jp_remove_admin_bar_edit_link() {
if( ! current_user_can( 'administrator' ) ) {
global $wp_admin_bar;
$wp_admin_bar->remove_menu( 'edit' );
}
}
add_action( 'wp_before_admin_bar_render', 'jp_remove_admin_bar_edit_link' );
Feel free to combine the two pieces of code. For more details about the Roles and Capabilities of WordPress, see this page.