Restrict admin access to certain pages based on page slug

by captainM   Last Updated May 20, 2020 00:08 AM

I'm trying to do exactly what is done with this question - Restrict admin access to certain pages for certain users

Except I want to use a page slug to restrict the users by. So instead of

$query->query_vars['post__not_in'] = array('123','234','345');

I want to be able to use

$query->query_vars['post__not_in'] = array('home','about-us','contact');

Appreciate the time.

Tags : wp-admin slug


Answers 1


Ok team, I figured this out and its real simple. Use get_page_by_path to retrieve pages and get their slugs and pass it as an array object which is converted to an array of post ids. Since home pages dont have slugs, I had to use get_option to grab the id of the front page and push that in the array.

 function hide_pages_in_admin($query) {

    // Create array of all the slugs you wanna hide
     $hidden_slugs = array( 'about-us', 'contact','404');

    // Loop through slugs & pass each slug as page path value
    foreach ($hidden_slugs as $hidden ) {

     $hidden_slugs[] = get_page_by_path( $hidden )->ID;

    // In case you need to hide the home page too
    $hidden_IDs[] += get_option('page_on_front');

    }

    // Select the user type to hide pages from
    if ( current_user_can('editor') ) {

       // Pass the array as value to the query vars filter 
      $query->query_vars['post__not_in'] =  $hidden_slugs;

    }
 }

add_filter( 'parse_query', 'hide_pages_in_admin');

captainM
captainM
May 19, 2020 23:49 PM

Related Questions





Admin blank page after I changed custom post type

Updated July 26, 2018 08:08 AM