Should custom user capabilities be added before the custom user role has been added, or the other way around?

  • add_role() asks for and array of $capabilities in the third
    parameter of the function.
  • add_cap() asks for a $role to apply the capability to in the
    first parameter of the function.

Both add_role() and add_cap() need to be fired on plugin activation or theme activation.

I was thinking, create the custom user capabilities using add_cap() and store the list of capabilities in a class property array. Then, create each custom user role using add_role(), and add the newly created capabilities from the class property array into the $capabilities parameter of each add_role() function.

OR

I would add each custom user role using add_role() and set a class property array of each of the capabilities for the role to add. Then, for each of the capabilities for each custom user role, I would add the capability using add_cap().

The order of which to perform both add_role() and add_cap() in harmony puzzles me. Any insight on this particular situation is appreciated.

Or should I just not even use add_cap()? Can I just setup an array of capabilities for each user role, and just pass them into the $capabilities parameter of the add_role() function?

2 s
2

There’s a reason why add_role() has the $capabilities as 3rd parameter.

First some insights on what happens, when you use the function.

  1. It calls WP_Roles->add_role() – the class method
  2. The method then does a check if the role already exists. If yes, it aborts.
  3. The next step is, that it adds the role to WP_Roles->roles[] array with the display_name (2nd arg) to the $wpdb->prefix . 'user_roles' option table entry (an array).

Conclusion

So if you don’t add the capabilities right when creating the role, then you save a role with empty capabilities.

A note about the Codex

NEVER EVER trust the codex. There simply is no function called add_cap(). There’re only class methods inside WP_Roles, WP_Role and WP_User that are named like this. (Will update the Codex entry if I find some time.)

Leave a Reply

Your email address will not be published. Required fields are marked *