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" ) { return; } if ( current_user_can( 'administrator' ) ) { return; } 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.
- Checks that the post variable “action” is set to attachment. This is because wordpress uses ajax with post vars to build the page.
- It checks that the user is not an administrator. Administrators can see everything (you can modify that if other users also must see everything).
- 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.
John, a seasoned Freelance Full Stack Developer based in South Africa, specialises in delivering bespoke solutions tailored to your needs. With expertise in back end languages and frameworks, PHP, Laravel and Golang and Front end frame words Vue3, Nuxt3 as well as Angular, I am equipped to tackle any project, ensuring robust, scalable, and cutting-edge outcomes.
My comprehensive skill set enables me to provide exceptional freelance services both remotely and in person. Whether you’re seeking to develop an innovative application or require meticulous refinement of existing systems, I am dedicated to elevating your digital presence through unparalleled technical prowess and strategic development methodologies. Let’s connect to transform your vision into reality.
One thought on “Show only user’s own media files in WordPress”
Awesome, it worked (even in Jan 2020)! – Two years after your post’s publish date.
Thank you for this.