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.
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:
[snippet slug=wordpress-view-only-own-media lang=php]
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 is a freelance Full Stack Developer. Experienced in PHP, Laravel and Vue3/Nuxt3 he can code anything you need.
Based in South Africa, I am available for PHP, Laravel or Vue3/Nuxt3 freelance jobs in person or remotely.