Comment créer une capacité de rôle personnalisée?
-
-
Unblog détaillé: http://goo.gl/xNuafHA detail blog: http://goo.gl/xNuafH
- 0
- 2016-01-14
- Suresh Kamrushi
-
3 réponses
- votes
-
- 2011-11-30
Supprimez ce que vous ajoutez
Tout d'abord,assurez-vous quetout ce que vous ajoutez lors de l'activation est également supprimé lors de la désinstallation . J'ai un courttutoriel comprenant unexemple de code pour vous.
Test avec unpetit plugin:
Jene sais vraimentpasgrand-chose sur MU,maispour autant queje sache,l'objet de rôlesestglobal surtous lesblogs. Essayez simplement cepetit pluginet voyez ce que vouspouvez obtenir:
<?php /* Plugin Name: MU Roles check Plugin URI: https://github.com/franz-josef-kaiser/ Description: Check roles during viewing a blog Author: Franz Josef Kaiser Author URI: https://plus.google.com/u/0/107110219316412982437 Version: 0.1 Text Domain: murc License: GPL v2 - http://www.gnu.org/licenses/old-licenses/gpl-2.0.html */ /** * Show the blog data and the role names in this blog * Also shows if the custom capability was successfully added, or displays n/a for the role * * @return void */ function wpse35165_role_check() { $blog = get_current_site(); $custom_cap = 'name_of_your_custom_capability'; $html = "<hr /><table>"; $html .= "<caption>List roles in (Blog) {$blog->site_name} / ID#{$blog->id}</caption>" $html .= "<thead><tr><th>Role Name</th><th>Capabilties</th></tr></thead><tbody>"; foreach ( $GLOBALS['wp_roles'] as $name => $role_obj ) { $cap = in_array( $custom_cap, $role_obj->caps ) ? $custom_cap : 'n/a'; $cap = $cap OR in_array( $custom_cap, $role_obj->allcaps ) ? $custom_cap : 'n/a'; $html .= "<tr><td>{$name}</td><td>{$cap}</td></tr>"; } $html .= '</tbody></table>'; print $html; } add_action( 'shutdown', 'wpse35165_role_check' );
Ajout de capacités
/** * Add the capability to the role objects * Should be in your activation function and done before you inspect with your plugin * * @return void */ function wpse35165_add_cap() { $custom_cap = 'name_of_your_custom_capability'; $min_cap = 'the_minimum_required_built_in_cap'; // Check "Roles and objects table in codex! $grant = true; foreach ( $GLOBALS['wp_roles'] as $role_obj ) { if ( ! $role_obj->has_cap( $custom_cap ) AND $role_obj->has_cap( $min_cap ) ) $role_obj->add_cap( $custom_cap, $grant ); } }
Remarque: Vouspouvez ajouter la capacité au rôle sans lui accorder l'accès -il suffit de définir le deuxième argument
$grant = false;
. Celapermet d'ajouter des utilisateurs uniques à la listeblancheen ajoutant simplement la limiteen incluant le dernier argument comme vrai.Remove what you add
First, please make sure that everything you add on activation also gets removed on uninstall. I got a short tutorial including example code for you.
Test with a small plugin:
I really don't know much about MU, but as far as I can tell, the roles object is global across all blogs. Just try this little plugin and see what you can get:
<?php /* Plugin Name: MU Roles check Plugin URI: https://github.com/franz-josef-kaiser/ Description: Check roles during viewing a blog Author: Franz Josef Kaiser Author URI: https://plus.google.com/u/0/107110219316412982437 Version: 0.1 Text Domain: murc License: GPL v2 - http://www.gnu.org/licenses/old-licenses/gpl-2.0.html */ /** * Show the blog data and the role names in this blog * Also shows if the custom capability was successfully added, or displays n/a for the role * * @return void */ function wpse35165_role_check() { $blog = get_current_site(); $custom_cap = 'name_of_your_custom_capability'; $html = "<hr /><table>"; $html .= "<caption>List roles in (Blog) {$blog->site_name} / ID#{$blog->id}</caption>" $html .= "<thead><tr><th>Role Name</th><th>Capabilties</th></tr></thead><tbody>"; foreach ( $GLOBALS['wp_roles'] as $name => $role_obj ) { $cap = in_array( $custom_cap, $role_obj->caps ) ? $custom_cap : 'n/a'; $cap = $cap OR in_array( $custom_cap, $role_obj->allcaps ) ? $custom_cap : 'n/a'; $html .= "<tr><td>{$name}</td><td>{$cap}</td></tr>"; } $html .= '</tbody></table>'; print $html; } add_action( 'shutdown', 'wpse35165_role_check' );
Adding Capabilities
/** * Add the capability to the role objects * Should be in your activation function and done before you inspect with your plugin * * @return void */ function wpse35165_add_cap() { $custom_cap = 'name_of_your_custom_capability'; $min_cap = 'the_minimum_required_built_in_cap'; // Check "Roles and objects table in codex! $grant = true; foreach ( $GLOBALS['wp_roles'] as $role_obj ) { if ( ! $role_obj->has_cap( $custom_cap ) AND $role_obj->has_cap( $min_cap ) ) $role_obj->add_cap( $custom_cap, $grant ); } }
Note: You can add the capability to the role without granting access to it - just set the second argument
$grant = false;
. This allows whitelisting single users with simply adding the cap including the last argument as true. -
- 2013-03-14
Pour unplugin sur lequelje travaille actuellement,je voulais accorder/restreindre l'accès auxparamètres duplugin (c'est-à-dire,lespages demenu d'administration correspondantes) sur unebase par rôle .
Par conséquent,j'ai dû ajouter unenouvellecapability
spécifique auplugin auxuser roles
.Malheureusement,la réponse de kaiser ne sembleplusfonctionner,j'ai doncpassé un certaintemps àessayer de comprendre commentpourpermettre lafonctionnalitémentionnée ci-dessus.
Le calendrier
Avant departagermon code avec vous,voici de quoiil s'agit,en textebrut:
- Lors de l'activation duplugin,ajoutez lanouvellefonctionnalité
THE_NEW_CAP
aux rôles ayant une certaine capacitéintégréeBUILT_IN_CAP
(dansmon cas:edit_pages
) . - À chaque chargement depage,effectuez 1. (c'est-à-dire,ajoutez ànouveau la capacité). Celan'estnécessaire que si vous souhaiteztenir compte d'éventuelsnouveaux rôles créés après l'activation duplugin. Par conséquent,cesnouveaux rôlesn'ontpas la capacité spécifique auplugin,même s'ils ont la capacitéintégrée requise.
- Utilisez lanouvellefonctionnalitépourtout ce que vous voulez. Commeexpliquéprécédemment,je l'utilisepour accorder/restreindre l'accès auxpages dumenu d'administration duplugin,c'est ainsi que cela sefait dans l'exemple de code suivant.
- Lors de la désactivation duplugin,supprimez la capacité. Bien sûr,vouspouvez également lefaire lorsque lepluginesten cours de désinstallation. Quoi qu'ilen soit,faites-le éventuellement.
Le code
Et voici la liste ci-dessus convertieen code:
»Configuration
class WPSE35165Plugin { public function __construct() { // Register hooks register_activation_hook(__FILE__, array(__CLASS__, 'activation')); register_deactivation_hook(__FILE__, array(__CLASS__, 'deactivation')); // Add actions add_action('admin_menu', array(__CLASS__, 'admin_menu')); } public function activation() { self::add_cap(); } // Add the new capability to all roles having a certain built-in capability private static function add_cap() { $roles = get_editable_roles(); foreach ($GLOBALS['wp_roles']->role_objects as $key => $role) { if (isset($roles[$key]) && $role->has_cap('BUILT_IN_CAP')) { $role->add_cap('THE_NEW_CAP'); } } }
»Utilisation
// Add plugin menu pages to admin menu public function admin_menu() { // Remove the following line if you don't care about new roles // that have been created after plugin activation self::add_cap(); // Set up the plugin admin menu add_menu_page('Menu', 'Menu', 'THE_NEW_CAP', …); add_submenu_page('wpse35165', 'Submenu', 'Submenu', 'THE_NEW_CAP', ...); }
»Lenettoyage
public function deactivation() { self::remove_cap(); } // Remove the plugin-specific custom capability private static function remove_cap() { $roles = get_editable_roles(); foreach ($GLOBALS['wp_roles']->role_objects as $key => $role) { if (isset($roles[$key]) && $role->has_cap('THE_NEW_CAP')) { $role->remove_cap('THE_NEW_CAP'); } } } }
Remarque: veuillezne pas utiliser lesfonctionnalitésmajuscules. C'estjustepour la lisibilité.
For a plugin I'm currently working on, I wanted to grant/restrict access to the plugin settings (i.e., the according admin menu pages) on a per role base.
Therefore, I had to add a new plugin-specificcapability
to theuser roles
.Unfortunately, kaiser's answer seems to be not working anymore, so I spent some time trying to figure out how to allow for the above mentioned functionality.
The Schedule
Before I share my code with you, here is what it's all about, in plain text:
- On plugin activation, add the new capability
THE_NEW_CAP
to roles having a certain built-in capabilityBUILT_IN_CAP
(in my case:edit_pages
). - On each page load, do 1. (i.e., add the capability, again). This is only necessary if you want to account for possible new roles that have been created after the activation of the plugin. Hence, these new roles don't have the plugin-specific capability, even if they have the required built-in capability.
- Use the new capability for whatever you want. As explained before, I use it for granting/restricting access to the plugin's admin menu pages, so that is how it is done in the following code example.
- On plugin deactivation, remove the capability. Of course, you could also do this when the plugin is being uninstalled. Either way, do it eventually.
The Code
And here is the above list converted into code:
» Setting It Up
class WPSE35165Plugin { public function __construct() { // Register hooks register_activation_hook(__FILE__, array(__CLASS__, 'activation')); register_deactivation_hook(__FILE__, array(__CLASS__, 'deactivation')); // Add actions add_action('admin_menu', array(__CLASS__, 'admin_menu')); } public function activation() { self::add_cap(); } // Add the new capability to all roles having a certain built-in capability private static function add_cap() { $roles = get_editable_roles(); foreach ($GLOBALS['wp_roles']->role_objects as $key => $role) { if (isset($roles[$key]) && $role->has_cap('BUILT_IN_CAP')) { $role->add_cap('THE_NEW_CAP'); } } }
» Using It
// Add plugin menu pages to admin menu public function admin_menu() { // Remove the following line if you don't care about new roles // that have been created after plugin activation self::add_cap(); // Set up the plugin admin menu add_menu_page('Menu', 'Menu', 'THE_NEW_CAP', …); add_submenu_page('wpse35165', 'Submenu', 'Submenu', 'THE_NEW_CAP', ...); }
» Cleaning It Up
public function deactivation() { self::remove_cap(); } // Remove the plugin-specific custom capability private static function remove_cap() { $roles = get_editable_roles(); foreach ($GLOBALS['wp_roles']->role_objects as $key => $role) { if (isset($roles[$key]) && $role->has_cap('THE_NEW_CAP')) { $role->remove_cap('THE_NEW_CAP'); } } } }
Note: Please do not use upper case capabilities. This is just for readability.
-
Utiliseztoujours `get_editable_roles ()`pour récupérer les rôles que vous souhaitezmodifier.Sinon,vous ** casserez ** lesplugins.Always use `get_editable_roles()` to fetch roles you want to edit. You **will** break plugins otherwise.
- 1
- 2013-04-28
- fuxia
-
@toscho Ehbien,d'accord,je suppose que c'est l'une de cesfonctions quemême le Codexne connaîtpas ...;) Bien sûr,cettefonction a le droit d'exister,cependant,je ne voispas l'utilisation dutableauglobal WP_Roles _breakingtous lesplugins_ dansmon cas.@toscho Well, okay, I suppose that's one of these functions even the Codex doesn't know about... ;) Of course, this function has its right to exist, however, I don't see using the global WP_Roles array _breaking any plugins_ in my case.
- 1
- 2013-04-28
- tfrommen
-
Certainsplugins créent des rôles d'utilisateur spécialiséset s'appuient sur l'ensembleexact de capacités.Dans certains cas,une capacitéexclut l'utilisation d'une autre dans la logique duprogramme.Vousne pouvezpas savoir quand c’est le cas.Some plugins create specialized user roles and rely on the exact set of capabilities. In some cases one capability excludes the usage of another in the program logic. You cannot know when that’s the case.
- 2
- 2013-04-28
- fuxia
-
- 2018-08-31
Celafonctionnepourmoi:
add_action('admin_init', 'add_custom_cap'); function add_custom_cap() { $custom_cap = 'test_cap'; $min_cap = 'read'; $grant = true; $to_role = 'your_user_role'; $role = 'user_role'; foreach ( $GLOBALS['wp_roles'] as $role_obj ) { if (is_object($role_obj[$role])) { if (!$role_obj[$role]->has_cap( $custom_cap ) && $role_obj[$role]->has_cap( $min_cap )) { $role_obj[$role]->add_cap( $custom_cap, $grant ); } } } }
This works for me:
add_action('admin_init', 'add_custom_cap'); function add_custom_cap() { $custom_cap = 'test_cap'; $min_cap = 'read'; $grant = true; $to_role = 'your_user_role'; $role = 'user_role'; foreach ( $GLOBALS['wp_roles'] as $role_obj ) { if (is_object($role_obj[$role])) { if (!$role_obj[$role]->has_cap( $custom_cap ) && $role_obj[$role]->has_cap( $min_cap )) { $role_obj[$role]->add_cap( $custom_cap, $grant ); } } } }
-
Nemodifiezjamais les *globaux * des rôles!Jamais.Pas!Vousne déclencherez aucun hook,refuserez lesfiltreset ferez de votre code une ciblemobile.Personnene saurajamais quandet où vous avezenregistré ce rôle (vousne l'avezpasfait,vous l'avez simplementfourré quelquepart,quelquepart,d'unemanière ou d'une autre).S'il vousplaît:ne faitesjamais ça.Surtoutpas avec les rôles.Do not ever modify the *globals* of roles! Never. Don't! You will not trigger any hooks and deny filters and make your code a moving target. No one will ever know when and where you registered that role (you did not, you just stuffed it in there somewhere, somewhen, somehow). Please: Do not ever do that. Especially not with roles.
- 0
- 2019-10-13
- kaiser
Je souhaite créer unefonctionnalitépersonnaliséepour accéder à l'interface demonplugin.