My new best friend: ajax_query_attachments_args

I’m working on a site were users will have extra fields in their profiles, among them, a user picture. To achieve this, I used Advanced Custom Fields. Easy peasy lemon squeezy!

The problem was that when a user went to upload or chose a file for their picture profile, it showed all media files, from every user. Not ideal for this particular site (we are using some custom roles that let people upload pictures, but not create entries).

After some googlin’ I found many references (here, and here, for example ) to this code:

It works quite well when you want people to only see their own uploads in the media library. You can even modify it to also work in other pages, so I changed the code to apply also in the user.php page.

My problem was that those handy fields I added with Advanced Custom Fields count as posts authored by another user, therefore, no new user fields. Darn! So close…

Not too happy, I looked far and wide online, but found nothing useful, until rummaging through the, I found ajax_query_attachments_args:

Filter the arguments passed to WP_Query during an AJAX call for querying attachments.
@since 3.7.0
@param array $query An array of query variables. @see WP_Query::parse_query()

Which means that the filter will only affect the list of attachments when viewed with the ajax image uploader, which is exactly what would happen in user.php.

I would still need the first code to limit the list of posts in the media library (uploads.php), but now I have a way to filter for the ajax media library only.

One Response to “My new best friend: ajax_query_attachments_args”