Restreindre les utilisateurs à afficher uniquement les éléments de bibliothèque multimédia qu'ils ont téléchargés?
-
-
Si vous aveztrouvé une réponse à votrepropreproblème,vousferiezmieux de l'ajouter comme réponse ci-dessous,pas dans la questionelle-même.Cela correspondmieux au systèmeet nouspouvons voterpour votre réponse,ce qui améliorera votre réputation sur ce site.If you found an answer to your own problem, you better add it as an answer below, not in the question itself. This is better in line with the system, and we can up-vote your answer, which will improve your reputation on this site.
- 1
- 2010-09-09
- Jan Fabry
-
http://wordpress.org/plugins/view-own-posts-media-only/http://wordpress.org/plugins/view-own-posts-media-only/
- 1
- 2013-07-25
- Ramji
-
Je dois vraiment appuyer leplugin 'View Own Posts Media Only',cela aparfaitementfonctionnépourmoi après avoir cherchépartout une solutionjquery ouphp/html/css.I really have to second the 'View Own Posts Media Only' plugin, it worked perfectly for me after looking everywhere for a jquery or php/html/css solution.
- 0
- 2014-03-04
- waffl
-
8 réponses
- votes
-
- 2010-11-20
Vouspouveztoujoursfiltrer la liste desmédiasen utilisant unfiltre
pre_get_posts
qui détermine d'abord lapageet les capacités de l'utilisateur,et définit leparamètre auteur lorsque certaines conditions sont remplies.Exemple
add_action('pre_get_posts','users_own_attachments'); function users_own_attachments( $wp_query_obj ) { global $current_user, $pagenow; $is_attachment_request = ($wp_query_obj->get('post_type')=='attachment'); if( !$is_attachment_request ) return; if( !is_a( $current_user, 'WP_User') ) return; if( !in_array( $pagenow, array( 'upload.php', 'admin-ajax.php' ) ) ) return; if( !current_user_can('delete_pages') ) $wp_query_obj->set('author', $current_user->ID ); return; }
J'ai utilisé la limite de suppression despages comme conditionpour que les administrateurset les éditeurs voienttoujours la liste complète desmédias.
Il y a unpetit effet secondaire,pour lequelje ne vois aucun hook,et c'est avec lenombre depiècesjointes affiché au-dessus de la liste desmédias (qui afficheratoujours lenombretotal d'élémentsmultimédias,pas celui de l'utilisateur donné - Je considérerais cela comme unproblèmemineur).
J'aipensé queje lepublieraistout demême,celapourrait être utile ..;)
You could always filter the media list using a
pre_get_posts
filter that first determines the page, and the capabilities of the user, and sets the author parameter when certain conditions are met..Example
add_action('pre_get_posts','users_own_attachments'); function users_own_attachments( $wp_query_obj ) { global $current_user, $pagenow; $is_attachment_request = ($wp_query_obj->get('post_type')=='attachment'); if( !$is_attachment_request ) return; if( !is_a( $current_user, 'WP_User') ) return; if( !in_array( $pagenow, array( 'upload.php', 'admin-ajax.php' ) ) ) return; if( !current_user_can('delete_pages') ) $wp_query_obj->set('author', $current_user->ID ); return; }
I used the delete pages cap as a condition so Admins and Editors still see the full media listing.
There is one small side effect, which i can't see any hooks for, and that's with the attachment counts shown above the media list(which will still show the total count of media items, not that of the given user - i'd consider this a minor issue though).
Thought i'd post it up all the same, might be useful.. ;)
-
J'ai autorisé letéléchargement defichiers aux utilisateurs deniveau abonné.aessayé d'utiliser votre codemaisne fonctionnepas.I have allowed file upload to subscriber level users. tried to use your code but not working.
- 0
- 2012-05-06
- Sisir
-
«Nefonctionnepas»n'estpasgrand-chose à dire."Not working" isn't much to go on.
- 1
- 2013-08-08
- t31os
-
Jepeux confirmer lamême observation.Pourmoi,"nefonctionnepas" signifie que le rôle "contributeur"peuttoujours voirtous les élémentsmultimédias lorsqu'il vatélécharger unjpg.Cependant,lorsqu'il accède à lamédiathèque àpartir dumenu,ilest vide.(_Mon rôle de «contributeur» a déjà la capacité supplémentaire detélécharger desfichierset celafonctionne._)I can confirm the same observation. For me "not working" means that the "contributor" role can still see all media items when he goes to upload a jpg. However, when he goes to media library from the menu, it's empty. (_My "contributor" role already has the extra capability to upload files and that's working._)
- 0
- 2014-02-03
- Sparky
-
Donc,votre code ajustebesoin d'êtremodifiépourn'importe quellepage remplissant l'onglet "Médiathèque" de lafenêtre detéléchargement.Je recherche çamaintenant.So your code just needs to be tweaked for whatever page fills the "Media Library" tab of the upload window. I'm researching this now.
- 0
- 2014-02-03
- Sparky
-
Sije me souviensbien (et deserreurs seproduisent),iln'y avaitpas de crochets appropriésen place aumoment de la rédaction de cette réponse,de lamêmemanière qu'aucun crochetn'étaiten placepour corriger lenombre demédias.Il y aeu 3bonnesnouvelles versions de WordPress depuis lemoment de la rédaction,donc des solutionspeuventmaintenant êtrepossibles.If i recall correctly(and mistakes do happen), there was not any appropriate hooks in place at the time of writing this answer, similarly to how no hooks were in place to fix the media count. There's been a good 3 new versions of WordPress since the time of writing however, so solutions may now be possible.
- 0
- 2014-02-03
- t31os
-
Deplus,ilpourrait simplement s'agir demettre àjour la vérification conditionnelle `$pagenow`,car cela vise à cibler la requête spécifiquementpour lapageprincipale desmédias,quin'estpas lamême que l'ongletmédia de lafenêtre detéléchargement.Additionally, it could just be a matter of updating the `$pagenow` conditional check, as this aims to target the query specifically for the main media page, which is not one and the same as the media tab on the upload popup.
- 0
- 2014-02-03
- t31os
-
Jeme fiche que les comptes soientfaux.Sinon,votre codefonctionne àpartir de l'élément Média dans lemenu (WP v3.8.1).J'essaie defairefonctionner cela àpartir de lafenêtre detéléchargement qui apparaît àpartir de lapage "Nouveaumessage".Oui,je suis d'accord ... J'essaie detrouver labonnepagepour le contrôle `$pagenow`.I don't care about the counts being wrong. Otherwise, your code is working from the Media item in the menu (WP v3.8.1). I'm trying to get this working from the upload window that pops up from within the "New Post" page. Yes, I agree... I'm trying to find the correct page for the `$pagenow` check.
- 0
- 2014-02-03
- Sparky
-
Voici la solution: http://wordpress.stackexchange.com/a/132319/11092Here is the solution: http://wordpress.stackexchange.com/a/132319/11092
- 0
- 2014-02-03
- Sparky
-
`if (!in_array ($pagenow,array ('upload.php','admin-ajax.php')` Ilmanque un crochetfermant à cette ligne dans votre code `)`,Il devrait yen avoirtrois `)`,mais votrele coden'en a que deux.`if( !in_array( $pagenow, array( 'upload.php', 'admin-ajax.php' )` This line in your code is missing a closing bracket `)` , There should be three `)`, but your code has only two.
- 0
- 2016-12-10
- Ibrahim
-
Celane semble s'appliquer qu'à la vueen grille.Des recommandations sur lafaçon d'accomplir celapour la vue liste également?This only seems to apply to the grid view. Any recommendations on how to accomplish this for the list view as well?
- 0
- 2017-11-08
- Dedering
-
Solution àma question ci-dessus: `if (('upload.php'!=$ Pagenow) && ('admin-ajax.php'!=$ Pagenow|| $ _REQUEST ['action']!='Query-attachments')) »Solution to my question above: `if( ('upload.php' != $pagenow ) && ( 'admin-ajax.php' != $pagenow || $_REQUEST['action'] != 'query-attachments' ) )`
- 0
- 2017-11-08
- Dedering
-
- 2015-02-21
Depuis WP 3.7,ilexiste unbien meilleurmoyen via lefiltre
ajax_query_attachments_args
,commefourni dans le documentation :add_filter( 'ajax_query_attachments_args', 'show_current_user_attachments' ); function show_current_user_attachments( $query ) { $user_id = get_current_user_id(); if ( $user_id ) { $query['author'] = $user_id; } return $query; }
As of WP 3.7 there is a much better way via the
ajax_query_attachments_args
filter, as provided in the documentation:add_filter( 'ajax_query_attachments_args', 'show_current_user_attachments' ); function show_current_user_attachments( $query ) { $user_id = get_current_user_id(); if ( $user_id ) { $query['author'] = $user_id; } return $query; }
-
- 2014-02-03
Ceciest une versionmodifiée de la réponse acceptée . Étant donné que la réponse acceptéene cible que l'élément demenu Média sur lagauche,les utilisateurspeuventtoujours voirtoute labibliothèquemultimédia dans la zonemodale lors dutéléchargement d'unephoto dans unmessage. Ce code légèrementmodifié corrige cette situation. Les utilisateurs ciblésne verront leurspropres élémentsmultimédias que dans l'onglet Médiathèque de laboîtemodale qui apparaît dans unmessage.
Voici le code de la réponse acceptée avec un commentairemarquant la ligne àmodifier ...
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 ) // <-- let's work on this line return; if( !current_user_can('delete_pages') ) $wp_query_obj->set('author', $current_user->id ); return; }
Pour que les utilisateursne voient que leurspropresmédias àpartir dumenu Média ET de l'onglet Médiathèque dumode detéléchargement,remplacez la ligneindiquéepar ceci ...
if( ( 'upload.php' != $pagenow ) && ( ( 'admin-ajax.php' != $pagenow ) || ( $_REQUEST['action'] != 'query-attachments' ) ) )
( sauts de ligneet espacementinsérés uniquementpour la lisibilitéici )
Ce qui suitest lemême que ci-dessus,mais lesempêche également de voir leurspropresmessages àpartir de l'élément demenu Messages.
if( ( 'edit.php' != $pagenow ) && ( 'upload.php' != $pagenow ) && ( ( 'admin-ajax.php' != $pagenow ) || ( $_REQUEST['action'] != 'query-attachments' ) ) )
( sauts de ligneet espacementinsérés uniquementpour la lisibilitéici )
<↑ Notes : comme dans la réponse acceptée,lesmessageset les compteurs demédias seronterronés. Cependant,ilexiste des solutionspour cela dans d'autres réponses sur cettepage. Jene les aipasincorporés simplementparce queje ne les avaispastestés.
This is a modified version of the accepted answer. Since the accepted answer only targets the Media menu item on the left, users could still see the whole media library within the modal box when uploading a photo to a post. This slightly modified code fixes that situation. The targeted users will only see their own media items from the Media Library tab of the modal box that pops up within a post.
This is the code from the accepted answer with a comment marking the line to edit...
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 ) // <-- let's work on this line return; if( !current_user_can('delete_pages') ) $wp_query_obj->set('author', $current_user->id ); return; }
For users to only view their own media from Media menu AND Media Library tab of the upload modal, replace the indicated line with this...
if( ( 'upload.php' != $pagenow ) && ( ( 'admin-ajax.php' != $pagenow ) || ( $_REQUEST['action'] != 'query-attachments' ) ) )
(line-breaks & spacing only inserted for readability here)
The following is the same as above but also restricts them to seeing their own posts from the Posts menu item.
if( ( 'edit.php' != $pagenow ) && ( 'upload.php' != $pagenow ) && ( ( 'admin-ajax.php' != $pagenow ) || ( $_REQUEST['action'] != 'query-attachments' ) ) )
(line-breaks & spacing only inserted for readability here)
Notes: as in the accepted answer, the posts and media counters will be wrong. However, there are solutions for this in some other answers on this page. I did not incorporate those simply because I had not tested them.
-
- 2011-11-26
Code detravail complet. Le seulproblèmeest d'obtenir unnombreincorrect d'images dans labibliothèquemultimédia sur lapage Ajouter un article.
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 ); } } else if ( strpos( $_SERVER[ 'REQUEST_URI' ], '/wp-admin/media-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' );
Complete working code.. Only issue is, getting wrong count of images in media library on Add Post page.
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 ); } } else if ( strpos( $_SERVER[ 'REQUEST_URI' ], '/wp-admin/media-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' );
-
Vousne devezpas utiliser lesniveaux utilisateur,ils sonttoujoursprincipalement dans WordPresspour la compatibilité ascendante (avant WP 2.0),ilsne sontpasfiablespour déterminer les capacités utilisateur dans WordPressmoderne (carils disparaîtrontprobablement dunoyau lorsque cette compatibiliténe seraplus requise).Utilisez une [capacité] réelle (http://codex.wordpress.org/Roles_and_Capabilities#Capability_vs._Role_Table)pour déterminer les droits des utilisateurs.You should not use user levels, they are in WordPress still primarily for backwards compatibility(prior to WP 2.0), they are not reliable for determining user capabilities in modern day WordPress(as they will likely disappear from core when that compatibility is no longer required). Use an actual [capability](http://codex.wordpress.org/Roles_and_Capabilities#Capability_vs._Role_Table) to determine user rights.
- 2
- 2014-01-28
- t31os
-
Bien qu'il contienne `media-upload.php`,votre codene fonctionnepas àpartir dumodal detéléchargementgénérépar lapage Post Edit.Peuttoujours voirtous les éléments de labibliothèque.Despite containing `media-upload.php`, your code is not working from the upload modal generated by the Post Edit page. Can still see all library items.
- 0
- 2014-02-03
- Sparky
-
- 2012-04-13
t31os a uneexcellente solution là-haut.La seule choseest que lenombre detous lesmessages s'affichetoujours.
J'aitrouvé unmoyen d'empêcher lenombre de s'afficheren utilisantjQuery.
Ajoutez simplement ceci à votrefichier defonction.
function jquery_remove_counts() { ?> <script type="text/javascript"> jQuery(function(){ jQuery("ul.subsubsub").find("span.count").remove(); }); </script> <?php } add_action('admin_head', 'jquery_remove_counts');
Celafonctionnepourmoi!
t31os has a great solution up there. The only thing is that the number of all the posts still shows up.
I figured out a way to keep the number count from showing up using jQuery.
Just add this to your function file.
function jquery_remove_counts() { ?> <script type="text/javascript"> jQuery(function(){ jQuery("ul.subsubsub").find("span.count").remove(); }); </script> <?php } add_action('admin_head', 'jquery_remove_counts');
It's working for me!
-
- 2010-09-10
J'ai résolumonproblème avec une solution assez approximative,mais réalisable.
1) J'aiinstallé leplugin WP Hide Dashboard,de sorte que l'utilisateurne verrait qu'un lien vers leformulaire demodification de sonprofil.
2) Dans lefichiermodèle author.php,j'aiinséré le code quej'ai utilisé ci-dessus.
3) Ensuite,pour les utilisateurs connectés,j'ai affiché un lien direct vers lapage detéléchargement "wp-admin/media-new.php"
4) Leproblème suivant quej'ai remarqué,c'est qu'après avoirtéléchargé laphoto,il les redirigeait vers upload.php ...et ilspouvaient voirtoutes les autresimages. Jen'aipastrouvé de crochet dans lapagemedia-new.php,alorsj'aifini parpirater lenoyau "media-upload.php"et les rediriger vers leurpage deprofil:
global $current_user; get_currentuserinfo(); $userredirect = get_bloginfo('home') . "/author/" .$current_user->user_nicename;
Puis remplacé
wp_redirect( admin_url($location) );
parwp_redirect($userredirect);
Quelquesproblèmes,cependant. Tout d'abord,l'utilisateur connectépeuttoujours accéder à "upload.php",s'il sait qu'ilexiste. Ilsne peuvent rienfaire sauf REGARDER lesfichiers,et 99% desgensne le saurontmêmepas,mais cen'esttoujourspas optimal. Deuxièmement,il redirige également l'administrateur vers lapage deprofil après letéléchargement. Ceux-cipeuvent avoir une solution assez simpleen vérifiant les rôles des utilisateurset en redirigeant uniquement les abonnés.
Si quelqu'un a desidéespour se connecter à lapage Média sansentrer dans lesfichiersprincipaux,je l'apprécierais. Merci!
I solved my problem with a pretty rough, but workable solution.
1) I installed the WP Hide Dashboard plugin, so the User would only see a link to their profile edit form.
2) In author.php template file, I inserted the code I used above.
3) Then, for logged in users, I displayed a direct link to the Upload page "wp-admin/media-new.php"
4) The next issue I noticed, was after they uploaded the photo, it would redirect them to upload.php... and they could see all the other pictures. I haven't found a hook into the media-new.php page, so I ended up hacking into the core "media-upload.php" and redirecting them to their profile page:
global $current_user; get_currentuserinfo(); $userredirect = get_bloginfo('home') . "/author/" .$current_user->user_nicename;
Then replaced
wp_redirect( admin_url($location) );
withwp_redirect($userredirect);
A couple of issues, though. First, the logged in user can still go to "upload.php", if they know it exists. They can't do anything except LOOK at the files, and 99% of people won't even know about it, but it's still not optimal. Second, it also redirect the Admin to the profile page after uploading. These can have a fairly simple fix by checking user roles, and only redirecting Subscribers.
If anyone has ideas about hooking into the Media page without going into the core files, I'd appreciate it. Thanks!
-
Il y a un hook `admin_init` qui s'exécute à chaque demande d'administrateur.Dans le cas où un utilisateur demande upload.phpet que vous voulez l'empêcher,vouspouvez soitbloquer cette demande (parexemple `wp_die ('Accès refusé')`) soit rediriger vers unendroit validepar hook.There is an `admin_init` hook that runs on every admin request. In case a user requests upload.php and you want to prevent that you could either block that request (e.g. `wp_die('Access Denied')`) or redirect to some valid place per hook.
- 2
- 2010-09-11
- hakre
-
- 2010-12-08
<?php /* Plugin Name: Manage Your Media Only Version: 0.1 */ //Manage Your Media Only function mymo_parse_query_useronly( $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', 'mymo_parse_query_useronly' ); ?>
Enregistrez le code ci-dessus sousmanage_your_media_only.php,zippez-le,téléchargez-leen tant queplugin sur votre WPet activez-le,c'esttout.
<?php /* Plugin Name: Manage Your Media Only Version: 0.1 */ //Manage Your Media Only function mymo_parse_query_useronly( $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', 'mymo_parse_query_useronly' ); ?>
Save code above as manage_your_media_only.php, zip it, upload as plugin to your WP and activate it, that's all.
-
- 2011-01-11
Unefaçon defaireest d'utiliser le plugin Role Scoper ,c'estgénialpourgérer également des rôleset des capacitéstrès spécifiques.Vouspouvezen fait verrouiller l'accès auximages de labibliothèquemultimédia uniquement à cellestéléchargéespar chaque utilisateur.Je l'utilisepour unprojet sur lequelje travailleen cemomentet celafonctionnebien.
One way of doing this is to use the Role Scoper plugin, it is great for managing very specific roles and capabilities too. You can actually lock access to images in the Media Library to only those uploaded by each user. I've been using it for a project that I'm working on at the moment and it works well.
Je souhaite que les utilisateurspuissenttélécharger desphotos à l'aide de
add_cap('upload_files')
mais dans leurpage deprofil,lamédiathèque affichetoutes lesimagestéléchargées.Commentpuis-jefiltrer cela afin qu'ilsne puissent voir que lesimages qu'ils onttéléchargées?Voicima solutionpour lemoment… Jefais une simple requête WP,puis uneboucle sur lapage "Profil" de l'utilisateur