X

Restringir a visualização pelos usuários apenas dos itens da biblioteca de mídia que eles carregam

Snippets by IsItWP

Está procurando uma maneira de restringir os usuários a visualizarem somente os itens da biblioteca de mídia que eles carregam? Embora provavelmente exista um plug-in para isso, criamos um trecho de código rápido que pode ser usado para restringir os usuários a visualizar apenas os itens da biblioteca de mídia que eles carregam no WordPress.

Instruções:

Tudo o que você precisa fazer é adicionar esse código ao arquivo functions.php do seu tema ou em um plug-in específico do site:

function my_files_only( $wp_query ) {
    if ( strpos( $_SERVER[ 'REQUEST_URI' ], '/wp-admin/upload.php' ) !== false ) {
        if ( !current_user_can( 'level_5' ) ) {
            global $current_user;
            $wp_query->set( 'author', $current_user->id );
        }
    }
}

add_filter('parse_query', 'my_files_only' );

Observação: Se esta é a primeira vez que você adiciona trechos de código no WordPress, consulte nosso guia sobre como adicionar corretamente trechos de código no WordPress, para não danificar seu site acidentalmente.

Se você gostou desse snippet de código, considere dar uma olhada em nossos outros artigos no site, como: 7 melhores serviços de VPN para usuários do WordPress e como criar um formulário de doação no WordPress.

Comentários   Deixe uma resposta

  1. we just realised that although this scripts works in web wordpress , however the android /mobile version of media library still viewable by everyone

  2. a small change I did in code to make it work on front end on my profile page

    //if ( false !== strpos( $_SERVER[ ‘REQUEST_URI’ ], ‘/wp-admin/upload.php’ ) ) {
    if ($wp_query->query_vars[‘post_type’]==”attachment”){

    this way it is working properly.

    1. Thanks Prasanna, i registered a Disqus account to just thank you.

      1. Me too

  3. My new best friend: ajax_query_attachments_args | Alicia Ramirez março 3, 2014 em 6:17 pm

    […] some googlin’ I found many references (here, and here, for example ) to this […]

  4. It worked! (WP 3.8.1) Thank you!

  5. hi, thanks for the code. very helpful!

    however, other users are still able to view the attachments if they have a direct link. is there a way to prevent this? as in only the owner of the media (and admin) are able to see the attachments. other users or public cant seem them.

    Thanks.

  6. I put that code… but have wrong counter for media post…

    Curent user not have media post … whi have that All (15) | Images (15) | Unattached (2)

    i want show count for curent user.. not for all….

    1. I just hide all count numbers by css: subsubsub .count {display: none; }

  7. ?afak SARAÇO?LU maio 6, 2013 em 12:00 pm

    Çok te?ekkür ederim – Thank you

  8. Christopher Grasso abril 2, 2013 em 6:35 pm

    Thank you a ton for this…. Role scoper was messing with another plug in and thats the only feature i wanted was the images to be limited… Thanks for updating it to work with the new media library, it works flawlessly.

  9. Does anyone know how to restrict user also when they upload file from the insert or edit post? In fact when I press the Add Media button, the popup shows me the Media Library tab, with all the media uploaded by all users. I’m using the WP 3.5.1.
    Thanks!

    1. Look at my reply to designlabCPH above. Insert this function in your functions file, and the media library will be restricted to users’ own files only.

      1. It doesn’t work for me 🙁 I want users that are non-admins to be able to view only their own files, also when they are creating posts, only see their own images when they add featured images, etc

      2. It doesn’t work for me 🙁 I want users that are non-admins to be able to view only their own files, also when they are creating posts, only see their own images when they add featured images, etc

      3. It doesn’t work for me 🙁 I want users that are non-admins to be able to view only their own files, also when they are creating posts, only see their own images when they add featured images, etc

      4. It doesn’t work for me 🙁 I want users that are non-admins to be able to view only their own files, also when they are creating posts, only see their own images when they add featured images, etc

      5. It works now! Thank you so much!

  10. I used the Role Scoper plugin. I’ve been looking to do figure this out all day. Role Scoper will only allowed the logged in user to see their own content and own posts by default. You can change this if you want to as well. Private Media Library for Authors 😉

  11. Jashua Peter Grafstein outubro 9, 2012 em 5:17 pm

    is there a way to set up this line of code to restrict the media library for contributors only. That way contributors can only see media they upload and admins can see everything.

  12. is there a way to program this line of code to only apply this to specific membership levels? (i.e. contributors are only able to see their media uploads, but admins can see everything)

  13.  Using WP 3.3.1 and this is not working. Is their an update on the code? Thanks.

    1. Look at my reply above. I posted a function that will work with the new media manager (WP 3.5+)

  14. I have one question kevin, how to restrict contributor from uploading media?

    1. Hi Rian,
      On line 3 you will see “level_5” on this wordpress page is has details on what the user levels are you can just change that level. http://codex.wordpress.org/User_Levels#User_Level_5_2

      1. i didn’t notice that default role for contributor is can’t upload any media. i just try it last night.. haha.

        Thanks you very much Kevin! 🙂

        1. No problem anytime,

  15. Thanks Kevin,  it is very useful, but how to fix  ‘total number of files’ ?

    1. Glad to hear you like the snippet! Well the total is still correct since the files do exist, although I do see your point. Ill take a look into this in the near future see if I can post a snippet.

  16. thanks for the post. just what i was looking for. 
    i made a small change >> also add the file media-upload.php to this line of code. this will also filter the images /mediafiles above the wysiwyg editor.
    presta

    1. Hi Sheila,

      Where/What did you post code-wise in the media-upload.php file? I’m getting an error when I paste the code in. Thanks in advance!

  17. Found an issue, media library still showing full content at post insert media popup window. (same as other pages template too)

    however, I added get global $post, and add another condition for posts.

    ‘/wp-admin/media-upload.php?post_id=’.$post->ID.’&type=image&tab=library’

    but it didn’t work..

    1. I fixed this by adding a second clause
      “|| strpos( $_SERVER[ ‘REQUEST_URI’ ], ‘/wp-admin/media-upload.php’ ) !== false”

      1. How on earth do you get this to work in WP 3.5?

        I’ve tried everything (I belive, although I’m not a PHP coder) including adding your solution above – and I just can’t get it to work.

        I need that only Admins can see all media in the library pop-up, and everyone else (including editors) can only see their respective images…. Would you mind spelling it out for me? 🙂

        1. Use Role Scoper if you haven’t gotten it figured out yet man. It accomplishes this very issue. It’s by default when you install the plugin. Both the Media Library and posts. FYI

          1. I have spent hours today just to fix that users upload issue, and found that’s the only code that work. Thanks!

        2. You have to change a few parameters for this to work with the new media manager.

          You can use this function (notice that I created a “manage_media_library” capability. Only if the user has this, will they see other files than their own):

          add_action(‘pre_get_posts’,’ml_restrict_media_library’);
          function ml_restrict_media_library( $wp_query_obj ) {

          global $current_user, $pagenow;

          if( !is_a( $current_user, ‘WP_User’) )

          return;

          if( ‘admin-ajax.php’ != $pagenow || $_REQUEST[‘action’] != ‘query-attachments’ )

          return;

          if( !current_user_can(‘manage_media_library’) )

          $wp_query_obj->set(‘author’, $current_user->ID );

          return;

          }

          1. I was looking exactly for this: ‘admin-ajax.php’ != $pagenow || $_REQUEST[‘action’] != ‘query-attachments’
            thanks so much!

          2. Where did you put this?

          3. as a new plugin! good, this works for me!

          4. great code solution Patrick – fixed my issue pronto – I wish I had found this back in Dec. : ) thank you!

          5. I try your code in plugin, directly in function.php but it doesn’t work. I’ve WordPress 3.5.1 ans i want to use it in front end with the add media button of the wp_editor function.
            I’ve tried in wp-admin but it doesn’t work to.

            I’ve you any idea why it’s not working ???

          6. Used this, much kudos to you!

  18. This snippets is so helpful for my multi bloggers site. You should make it to WP plug-ins! thanks =)

    1. Cool glad you like the snippet, I’m not sure it is worth adding as a plugin although it could be setup as one.

      1. You should, I’m having hard time in the plug-ins pool finding this and end-up gave up and looking for external resources, that causes me to reached here. I love your blog, straight cut per purpose snippet. Learning a lot from here!
        You’d shined my day, Thanks Chard! =)

        1. No problem, Glad you like the website – visit regularly we post daily!

Adicionar um comentário

Ficamos felizes por você ter optado por deixar um comentário. Lembre-se de que todos os comentários são moderados de acordo com nossa política de privacidade, e todos os links são nofollow. NÃO use palavras-chave no campo do nome. Vamos ter uma conversa pessoal e significativa.

WordPress Launch Checklist

A lista de verificação definitiva para o lançamento do WordPress

Compilamos todos os itens essenciais da lista de verificação para o lançamento de seu próximo site WordPress em um ebook prático.
Sim, envie-me o livro eletrônico gratuito grátis!