I am using the following code to enable a hierarchical exclusion filtering system in the dashboard when users access post lists and media library. Admin posts & media are hidden to all users, while "teachers" and "students" have restrictions. Teachers may view they're own stuff and students data. students are restricted to their role-group.
The problem is that if a restricted user attempts to filter in the dashboard the post list, the action will be ignored because my filtering system will override.
There should be a way to apply my filtering system only when the users are not selecting an allowed filter. I see that the url changes on user filtering, adding some parameters but this is an unreliable system IMO.
Any idea?
//********** post & media lists filtered by user role & category ****************
function posts_for_current_role($query) {
global $students_allowed_cat;
global $teachers_allowed_cat;
global $pagenow;
if($query->is_admin && !current_user_can('administrator')) {
//$filtered_cat = '3,22';
$user = wp_get_current_user();
if( 'edit.php' == $pagenow ){
if ( in_array( 'teacher', (array) $user->roles ) ) {
//The user has the "teacher" role
$filtered_cat = $teachers_allowed_cat;
}
if ( in_array( 'student', (array) $user->roles ) ) {
//The user has the "student" role
$filtered_cat = $students_allowed_cat;
}
$query->set('cat', $filtered_cat);
}
if( in_array( $pagenow, array( 'upload.php', 'admin-ajax.php' ) ) ){
// hide media from admin
$query->set('author', '-1');
}
}
return $query;
}
if( !current_user_can('administrator') ){
add_filter('pre_get_posts', 'posts_for_current_role');