Checking User Roles And Capabilities In WordPress

Determining User Permissions

WordPress uses a robust system of user roles and capabilities to control access and permissions within a site. When building custom functionality, validating user permissions is an important step to ensure proper security and functionality.

Checking roles with get_role()

The get_role() function retrieves details on a specific user role. Calling it without parameters returns an array of all defined roles within a site. To check a specific role, pass the role name as a string parameter. It returns a WP_Role object containing that role’s details.

$admin = get_role('administrator'); 

echo $admin->name; //Administrator 

Viewing roles and capabilities

User roles group together sets of capabilities – permissions that affect what parts of the admin and site a user can access. Viewing both roles and capabilities allows context on what a user can do within WordPress.

The list_roles() function outputs an array of the existing roles and details:

$roles = list_roles();

foreach ($roles as $role) {

  echo $role['name'] . ': ' . implode(', ', $role['capabilities'] );

}

Example of getting user role

To retrieve information on a specific user’s roles, pass a user ID to the get_roles() function:

$user_info = get_userdata(123);
$roles = $user_info->roles;

if (in_array('administrator', $roles)) {
  // User has admin role
}

Checking Capabilities for Content

Capability checks give context on if content should be displayed or access given to certain site functionality or admin areas. WordPress ties capabilities to specific content types like posts or pages.

Using current_user_can()

The current_user_can() function checks if the current logged in user has a given capability. For example:

if (current_user_can('publish_posts')) {
  // Show new post form
} else {
  // Show message that user can't publish posts
}

Checking capabilities for posts

When working with post content, common capability checks include:

  • publish_posts
  • edit_posts
  • edit_others_posts
  • delete_posts
  • read_private_posts
$post_id = 12345;

if (current_user_can('edit_post', $post_id)) { 
   // Allow editing post 12345
}

Checking capabilities for pages

Pages use similar capabilities, substituting the post type for pages. Common page capabilities are:

  • publish_pages
  • edit_pages
  • edit_others_pages
  • delete_pages
  • read_private_pages
if (current_user_can('delete_pages')) {
  // Show links to delete existing pages 
}

Code examples of common capability checks

Other examples checking access for custom post types, managing themes/plugins, media operations and more:

// Check permission to delete media
if (current_user_can('delete_others_media')) {

} 

// Manage themes  
$access = current_user_can('install_themes');

// Activate/deactivate plugins
$access = current_user_can('activate_plugins'); 

// Custom post type permission  
$access = current_user_can('edit_contacts');

Customizing Roles and Capabilities

The roles and capabilities system allows customization to extend existing permissions or create entirely new ones. Custom roles can restrict access or enable new functionality as needed.

Adding and removing roles

The add_role() and remove_role() functions handle installing new or uninstalling unneeded roles:

// Add role
add_role('support_agent', 'Support Agent', array(
  'read' => true,
  'read_private_pages' => true,
  'edit_pages' => true,
  'delete_pages' => true 
));

// Remove role  
remove_role('support_agent');

Adding/removing capabilities

New capabilities can expand user permissions. They connect to roles through the function add_cap():

// Add new capability
$role = get_role('editor');  
$role->add_cap('upload_videos');

// Allow video uploads for editors
if (current_user_can('upload_videos')) { 
  // Show video upload form
} 

The remove_cap() function removes unwanted capabilities associated with a role:

  
$role = get_role('author');
$role->remove_cap('publish_posts'); // Authors can no longer publish 

Best practices for customization

When modifying default roles and capabilities:

  • Avoid removing capabilities from administrative roles
  • Test that customized roles retain needed capabilities
  • Check for plugins that may be affected by permission changes
  • Document any custom roles and capabilities added
  • Consider multisite limitations

Troubleshooting Permission Issues

In certain cases, users may lose access or experience login issues due to capability or role problems. Isolating and fixing the underlying permission conflict resolves it.

Debugging issues with plugins/themes

Recently added plugins or themes that alter default capabilities can cause conflicts. Testing while disabled narrows down the source. Hooks triggering excessive capability checks also negatively impact performance.

// Test plugin as source of issues  
add_filter('pre_update_option_active_plugins', function(){
  $plugins = get_option('active_plugins');
  unset($plugins[array_search('plugin-dir/plugin.php', $plugins)]);
  return $plugins;
});

Accounting for multisite limitations

In WordPress multisite, permission customization can only occur on a per-site basis via the network admin. Individual sites can’t alter Super Admin roles and capabilities.

Resetting roles and capabilities

If needed, the database can be queried directly to reset roles to WordPress defaults. Backups provide a restore point as well.

global $wpdb;
$wpdb->query("DELETE from $wpdb->usermeta WHERE meta_key LIKE %wp_capabilities%"); 

Leave a Reply

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