Dany Alves
Dany Alves

Reputation: 193

How to hide specific page (from wp-admin) for certain users in wp?

My Image

enter image description here

I just wanted to hide specific page for certain users.

function remove_menus(){
    // get current login user's role
    $roles = wp_get_current_user()->roles;
    // test role
    if( in_array('administrator',$roles)){
        remove_menu_page( 'edit-comments.php' ); //Posts
        remove_menu_page( 'tools.php' );
        remove_menu_page('edit.php');
        remove_menu_page('wpcf7');
    }
     
    }
    add_action( 'admin_menu', 'remove_menus' , 100 );

This what I am tried upto now and its working fine for all the page.

My question is I dont want to show home - Front page (Please see my image) If logged in user is not admin. and also I want to hide add new

Upvotes: 2

Views: 3887

Answers (2)

dineshkashera
dineshkashera

Reputation: 1502

You can use user's role capabilities and allow on the basis of role for add new items.

function manage_user_action() {

 // get current login user's role
    $roles = wp_get_current_user()->roles;
    
    if( !in_array('administrator',$roles)){
        //remove capabilities 
        $roles->remove_cap( 'edit_pages');
    }
   
    
}
add_action( 'admin_init', 'manage_user_action');

To Remove Page from list

function jp_exclude_pages_from_admin($query) {
 
   global $pagenow, $post_type;
 
  if ( !current_user_can( 'administrator' ) && $pagenow == 'edit.php' && $post_type == 'page' )
    $query->query_vars['post__not_in'] = array( '10'); // Enter your page IDs here

  //don't forget to the query
   return $query;
 
}
add_filter( 'parse_query', 'jp_exclude_pages_from_admin' ); 

For more help see this link : Click Here

Upvotes: 7

NJENGAH
NJENGAH

Reputation: 1277

I have extended @dineshkashera answer to target a specific user by ID and the code should be as follows :

function jp_exclude_pages_from_admin($query) {

       global $pagenow, $post_type;

       $current_user_id = get_current_user_id();

          if ( $current_user_id == 2 && $pagenow == 'edit.php' && $post_type == 'page' )
            $query->query_vars['post__not_in'] = array( '11', '12','13'  ); // Enter your page IDs here

    }
    add_filter( 'parse_query', 'jp_exclude_pages_from_admin' ); 

This code will get the user with ID of 2 and remove the pages IDs 11,12 and 13 from their WP page edit screen.

Upvotes: 0

Related Questions