0

Hi I have this code in my functions.php and its working well when the editor is viewing the Media library: http://example.com/wp-admin/upload.php

add_action('pre_get_posts','users_own_attachments');

function users_own_attachments( $wp_query_obj ) {

global $current_user, $pagenow;

if( !is_a( $current_user, 'WP_User') )
    return;

if ( 'upload.php' != $pagenow ) 
    return;

if( !current_user_can('delete_users') )
    $wp_query_obj->set('author', $current_user->ID );

return;
}

The above code will prevent other editors from viewing the images uploaded by other editors in the media library. Only the administrator can see all images uploaded. The editor can only see the images uploaded by themselves (not others).

Now here is the issue, when creating or editing a post, Wordpress has an "Add Media" button that will allow users to upload images to their gallery. But the code above does not work when the user will upload via "Add Media" popup. They can still see the images uploaded by other editors.

How is it possible to modify the above code so that it will still work when users are viewing images via the "Add Media" popup and not the media library? Thank you so much for your help.

1

If I correctly understand your question, you may try this

function wpse78084_show_media_by_current_author_only($query) {
  global $pagenow, $user_ID;

  if( 'upload.php' == $pagenow && !current_user_can('manage_options') )
    $query->set('author', $user_ID);

return $query;
}

if ( is_admin() )
  add_filter('pre_get_posts', 'wpse78084_show_media_by_current_author_only');
0

The feasible solution would be to run a conditional tag to determine if the user is viewing the add media popup, see it here: Conditional tag to determine if the user is viewing the Add Media (after clicking Add media button)

And then add it in additional to this statement:

if (( 'upload.php' != $pagenow ) || (is_viewing_media))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.