Skip to content

Instantly share code, notes, and snippets.

@AramZS
Last active February 14, 2017 19:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AramZS/5406719 to your computer and use it in GitHub Desktop.
Save AramZS/5406719 to your computer and use it in GitHub Desktop.
Look up WordPress roles by capabilities, instead of having to thread through the role object to check capabilities against every role.
function get_capabilities($cap = false){
# Get the WP_Roles object.
global $wp_roles;
# Set up array for storage.
$role_reversal = array();
# Walk through the roles object by role and get capabilities.
foreach ($wp_roles->roles as $role_slug=>$role_set){
foreach ($role_set['capabilities'] as $capability=>$cap_bool){
# Don't store a capability if it is false for the role (though none are).
if ($cap_bool){
$role_reversal[$capability][] = $role_slug;
}
}
}
# Allow users to get specific capabilities.
if (!$cap){
return $role_reversal;
} else {
return $role_reversal[$cap];
}
}
function get_role_by_capability($cap, $lowest = true, $obj = false){
# Get set of roles for capability.
$roles = get_capabilities($cap);
# We probobly want to get the lowest role with that capability
if ($lowest){
$roles = array_reverse($roles);
}
$the_role = array_shift(array_values($roles));
if (!$obj){
return $the_role;
} else {
return get_role($the_role);
}
}
# If we want to allow users to set access by role, we need to give
# the users the names of the roles, but WordPress needs a capability.
# This function lets you match the role with the first capability
# that only it can do, the defining capability.
function get_defining_capability_by_role($role_slug){
$caps = get_capabilities();
foreach ($caps as $slug=>$cap){
$low_role = get_role_by_capability($slug);
# Return the first capability only applicable to that role.
if ($role_slug == ($low_role))
return $slug;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment