Recently, I worked on a project where customers of a website would create their own listings and on those listings they were able to upload their own images for a listing image gallery. I was up for the task, so I quickly set the WordPress Media Uploader to the frontend submission area for an easy file uploads and image selections. We tested the implementation and everything was working just fine, however, when the client tested the media uploader, he could see my images and add them to his listing gallery. This was actually an issue, since we did not want to allow users to use other users images.
The problem
The problem we had was the WordPress Media Uploader allowed the users to view all uploaded files. Nobody wants to allow all users to use all files, so we needed a solution for this.
The solution
We needed a solution that will do at least one of two things:
- Restrict the users and allow them to view only the files they uploaded. In our case it was images.
- Restrict the users to view only the files uploaded to the listing(post).
After some research, looking for the best solution, I decided that using the 'ajax_query_attachments_args'
filter is the best approach to solving the problem. The 'ajax_query_attachments_args'
filter allows us to tweak the WP_Query before we get and display the attachments to the user. It gets the same query arguments as for a WP_Query, so it should not be hard for anybody with some WordPress knowledge to modify. So here is the code to solve our problem:
Each part is documented with its number and details. If you don’t need something, all you need to do is remove it. The code checks that the user has rights to upload files (1). Then checks for the post_id and retrieves the Post(3,4). Then limits the customisation to our custom post type (5). Then, we needed only listings authors to modify the listings, so the code limits modifications to the post author only(6). Only display images, as we need them for a gallery(7). No private image(8), no images from other posts(9) and no other user images(10).
That’s it. Copy, paste to a functions.php file for the code to work. If you have any questions and comments, please leave them below.