Restrict admin access to certain pages for certain users

All we need is an easy explanation of the problem, so here it is.

As the title says, I’d like to restrict back-end access to certain pages for certain users.

While doing a site with 45-50 pages, I realised it would be a much better user experience if the Page menu only listed those pages which the user should be able to change/update.

I’ve tried the plugins below to no avail. Advanced access manager has the functionality but does not work/is buggy on 3.5.1.

http://wordpress.org/extend/plugins/advanced-access-manager
http://wordpress.org/extend/plugins/role-scoper
http://wordpress.org/extend/plugins/adminimize
http://wordpress.org/extend/plugins/s2member

Code snippet in functions.php?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

This code seems to work well for me (in functions.php):

$user_id = get_current_user_id();
if ($user_id == 2) {
    add_filter( 'parse_query', 'exclude_pages_from_admin' );
}

function exclude_pages_from_admin($query) {
    global $pagenow,$post_type;
    if (is_admin() && $pagenow=='edit.php' && $post_type =='page') {
        $query->query_vars['post__not_in'] = array('123','234','345');
    }
}

Method 2

It won’t let me comment, so I’m adding this as a new answer.

The error:

Warning: “call_user_func_array() expects parameter 1 to be a valid callback, >function ‘exclude_pages_from_admin’ not found or invalid function name”.

… is due to the function being called only after the user_id is checked. So if you’re logged in NOT as that user, the function doesn’t exist, and the filter returns that error, since it is looking for the function, but can’t find it.

So it should be:

add_filter( 'parse_query', 'exclude_pages_from_admin' );

function exclude_pages_from_admin($query) {
    $user_id = get_current_user_id();

    if ($user_id == 2) {
    global $pagenow,$post_type;
     if (is_admin() && $pagenow=='edit.php' && $post_type =='page') {
        $query->query_vars['post__not_in'] = array('123','234','345');
     }
    }
}

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply