m4k3r-net
9/22/2018 - 9:39 PM

Allowing user to edit only certain pages

Allowing user to edit only certain pages

function my_pre_get_posts($query) {

  screen = get_current_screen();

  current_user = wp_get_current_user();

  $restricted_user_id = 10;
  $allowed_post_id = 1234;

  $current_post_id = isset($_GET['post'])?(int)$_GET['post']:false;

  if($current_user->ID !== $restricted_user_id) {
    return;
  }
  if(! $current_post_id) {
    return;
  }
  if($screen->id =='page'&& $current_post_id !== $allowed_post_id) {
    wp_redirect(admin_url());
    exit;
  }


  $restrictions_map = [10=>[123], 12311=>[152,186]];

  if( array_key_exists($current_user->ID, $restrictions_map)) {
    $allowed_posts = $restrictions_map[$current_user->ID];
    if($screen->id == 'page' && ! in_array($current_user->ID, $allowed_posts)) {
      if(array_key_exists($current_user->ID, $restrictions_map)) {
        $allowed_posts = $restrictions_map[$current_user->ID];
        if($screen->id =='page' && ! in_array($current_user->ID, $allowed_posts)) {
          wp_redirect(admin_url());
          exit;
        }
      }
    }

  }

  add_action('pre_get_posts','my_pre_get_posts');