Search code examples
phpwordpresswordpress-themingcustom-wordpress-pageswordpress-admin

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


Solution

  • 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