Show specific media for particular wordpress role

698 views Asked by At

I'm looking for ideas on how to go about only showing specific media to specific users.

I have created a new role and capability for that role in which I would like to attach specific media files to. So that the people in the new role can only view media that has been assigned to it.

In the end what I'm creating is a page that people will login to in order to download documents. I was hoping to have these documents pulled in dynamically, but if I can't figure out what I'm asking to do above I'll just hard code the documents to the page.

1

There are 1 answers

1
Ohgodwhy On

Well...as far as showing only certain media to certain users is concerned...

We can check where they're viewing their media at, if you're simply talking about the default Media Library within the WP-Admin interface, then we can check the URL to see if they're on a Media Library page.

We'll (likely) be placing this code in the functions.php file of our theme, or in our plugin, respective to your design.

//we need access to the $wp_query;
global $wp_query;

//now we build our function, we need to pass $wp_query into it
function manage_user_media($wp_query){

  //we check the location of the window
  if(strpos($_SERVER['REQUEST_URI'], '/wp-admin/upload.php') !== false ||
      strops($_SERVER['REQUEST_URI'], '/wp-admin/media-upload.php') !== false):

      //check if the logged in user has a capability of say...a level 5 user
      if(!current_user_can('level_5')):

          //this user does not have the capabilities of a level 5 user.
          //hijack the 'author' query var, so we can set it to the ID of our user
          $wp_query->set('author', get_current_user_id());

      endif;    

  endif;

}

If Wordpress User Levels are confusing to you, have a look at the Codex for comparison.

This means, that anyone over a level 5 user can see [ALL] media elements, where as anyone below a level 5 user, will only be able to view only [HIS OR HER] media elements.