schema-and-structured-data-for-wp
schema-and-structured-data-for-wp copied to clipboard
[Roles and Capabilities] Changing required capabilities based on roles
The way you use roles and capabilities in this plugin is a bit weird.
Normally in WordPress for Plugins you ideally use custom capabilities and then add those to the roles that should be able to do something. You shouldn't check for roles directly but instead always check for capabilities. Ideally ones specific to your plugin.
Just to summarize, what you do instead is having your own function that checks if a user is allowed to access: saswp_current_user_can()
. What this does is:
- First it checks if the user has one of the allowed roles as defined in the plugin settings: https://github.com/ahmedkaludi/schema-and-structured-data-for-wp/blob/d2be4865c36c02b5cd9dbb6e9d547b23ab7ecc60/admin_section/common-function.php#L3619-L3658 This is already a check for a role instead of a capability which shouldn't be done as mentioned above.
- If it has one of the allowed roles it continues to determine a capability in
saswp_get_capability_by_role()
https://github.com/ahmedkaludi/schema-and-structured-data-for-wp/blob/d2be4865c36c02b5cd9dbb6e9d547b23ab7ecc60/admin_section/common-function.php#L3586-L3617 But it does so only for the default roles and a very limited set of roles from common SEO plugins. For all others it falls back tomanage_options
. The main problem with this is that if you want to give any non-standard role that doesn't have themanage_options
capability access to the plugin settings it will not work. The only way to work around this is to use thesaswp_default_manage_option_capability
filter to change the default away frommanage_options
. But then you change it for everyone, unless you again change it based on the role of the current user which we should avoid in the first place.
Proposed Solution
So, what you should do instead is create a custom capability, e.g. manage_saswp_settings
and then just check for that. You could also (e.g. on activation of the plugin) add it to the default roles and custom roles by other plugins to match the current behavior in saswp_get_capability_by_role()
.
If you'd just do this adding access to users is very simple using add_cap
and allows you to skip all the nested checks of roles and changing capabilities while also adding more flexibility to use it the way WordPress intended.