Show only user’s own media files in WordPress

Show only user’s own media files in WordPress

The problem

I recently did a site for a client in wordpress which required a custom user type. These users needed to be able to use the media library but only to see their own media files.

One would have thought that this is actually quite a common scenario so I thought that implementing it would be simple enough…

In my research I came across a wordpress plugin called “View own posts media only”. This apparently worked well for a number of users but one user commented that because his users were of a custom type and his posts were custom posts types it did not work for him. This was my situation.

The solution

This post is already longer than I wanted it to be, so suffice it to say the solution was fairly simple.

There were various answers on sites like SO suggesting that you can use a filter but they never quite worked. I eventually managed to modify their suggestions to this:

function my_files_only( $wp_query )

        if ( ! $_POST["action"] == "attachment" )

        if ( current_user_can( 'administrator' ) )

        global $current_user;
        $wp_query->set( 'author', $current_user->id );


add_filter('parse_query', 'my_files_only' );

What does it do?

Its fairly straight forward but it modifies the wordpress query which gets the media to display.

  1. Checks that the post variable “action” is set to attachment. This is because wordpress uses ajax with post vars to build the page.
  2. It checks that the user is not an administrator. Administrators can see everything (you can modify that if other users also must see everything).
  3. Next it sets the author id in the query var to only retrieve that user’s media.


Suggestions / Comments?

Did this help? See an improvement? We’d love to hear from you in the comments.


One thought on “Show only user’s own media files in WordPress

Leave a Reply

Your email address will not be published. Required fields are marked *