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:
//This code works great in the media library page (upload.php).
function my_files_only( $wp_query ) {
if ( strpos( $_SERVER[ 'REQUEST_URI' ], '/wp-admin/upload.php' ) !== false ) {
if ( !current_user_can( 'manage_options' ) ) {
global $current_user;
$wp_query->set( 'author', $current_user->ID );
}
}
}
add_filter('parse_query', 'my_files_only' );
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.
//This code didn't really work, my custom fields disappeared.
function my_files_only( $wp_query ) {
if ( strpos( $_SERVER[ 'REQUEST_URI' ], '/wp-admin/upload.php' ) !== false
|| strpos( $_SERVER[ 'REQUEST_URI' ], '/wp-admin/user.php' ) !== false) {
if ( !current_user_can( 'manage_options' ) ) {
global $current_user;
$wp_query->set( 'author', $current_user->ID );
}
}
}
add_filter('parse_query', 'my_files_only' );
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 http://wphooks.info/, 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.
// Success!
function users_own_attachments_ajax( $wp_query_obj ) {
global $current_user;
if( ! current_user_can( 'manage_options' ) )
$wp_query_obj['author'] = $current_user->ID ;
return $wp_query_obj;
}
add_filter('ajax_query_attachments_args', 'users_own_attachments_ajax' );
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.
Glad I got a pingback for this post, Great post Alicia!