miguel.nz

Restrict users to see only their uploads in WordPress

May 27, 2020   |   1 minute read.

Sometimes you might want your users from your WordPress website to upload media files, you can easily handle this with user roles capabilities. However, once the user gets access by the upload_file role capabality, they will be able to see every file, all of them. So what about restricting media files to an specific user role?. Let’s check this out:

Modifying the author user role

Let’s say we have the ‘author’ user role and we only want them to access to their files. Our filter would then look like this:

add_action('pre_get_posts', function(){
  $current_user = wp_get_current_user();
  $is_attachment_request = ($query->get('post_type')=='attachment');

  if (!$is_attachment_request)
    return;

  if (!is_a( $current_user, 'WP_User'))
    return;

  if (in_array('author', (array) $current_user->roles)) {
    $query->set('author', $current_user->ID );
  }

  return;  
});

Additional Checks

You could add additional checks, for example you might want to restrict this only on the admin, front-end or under an specific page. Then you could look into is_page, $pagenow under the back-end, etc.