Get A User’S Roles And Capabilities By Id In WordPress

Determining the Need for User Role and Capability Checks

Understanding a WordPress user’s roles and capabilities is important for controlling access and permissions within a WordPress site. Checking a user’s roles and capabilities allows developers and site administrators to show or hide content and features selectively based on the user visiting the site.

Some common use cases where checking a user’s roles and capabilties is needed:

  • Showing admin links and dashboards only to administrators
  • Hiding paid content from non-subscribed users
  • Restricting access to pages, posts, or custom content types
  • Only allowing editing of certain posts and taxonomies by editors and administrators

By adding checks using WordPress current_user_can() function or getting the logged in user’s roles, plugins and themes can better manage permissions and access controls.

Why Check User Roles and Capabilities

WordPress comes with a robust user role and capability system to manage permissions for content, functionality, and assets within a site. Some key reasons to leverage these checks include:

  • Show relevant admin links, settings, and dashboards only to site administrators and editors
  • Hide paid or premium content from non-paying visitors
  • Allow granular access to pages, posts, custom post types based on user roles and capabilities
  • Selectively enable plugin functionality by role
  • Improve security by only allowing access and privileges as needed

Use Cases that Require Role and Capability Checks

Some examples of common use cases where role and capability checks are needed:

  • Dashboard Access – Only allow admins and editors to access WordPress dashboards
  • Post and Page Editing – Only allow editing by admins, editors, authors, and contributors
  • Premium Content – Only display paid posts, pages, custom post types to logged in paying subscribers
  • User Management – Only allow user management pages and functions to be accessed by administrators
  • Plugin Settings – Selectively show plugin settings only to users with activate_plugins capability

Finding a User’s ID

In order to retrieve information about a user’s roles and capabilities, we first need to determine the user’s ID within WordPress. This can be obtained for both the currently logged in user as well as other user accounts on the site.

Getting the Current User’s ID

The easiest way to get the current visitor’s user ID is with the get_current_user_id() function:

$current_user_id = get_current_user_id();

This will return the numeric ID for the user account associated with the current visitor if logged in. If not logged in, it returns 0.

Some key points on get_current_user_id():

  • Defined in wp-includes/pluggable.php
  • Returns user ID if logged in, 0 if no user is logged in
  • Useful for getting data specific to current user
  • Can be used with other user functions like get_userdata()

So with get_current_user_id(), we can easily get the current logged in WordPress user in just one line of code.

Getting Any User’s ID by Username

In some cases, you may need to get user data on users other than the current visitor. This is common when building admin dashboards and displays.

To get the user ID for any user account based on their username, we can use:

$user_id = get_user_by('login', $username)->ID;

This makes use of the get_user_by() function, passing the login value to match against the user login name / username.

Some key points on get_user_by():

  • Defined in wp-includes/capabilities.php
  • Takes search criteria and value as first params
  • Returns full user object containing ID, name, email, url, etc.
  • Useful when needing to get user data by criteria other than ID

So with get_user_by() we can find any matching user based on not only username, but also email, URL, ID, and more. It provides more flexibility to find users compared to just get_userdata().

Retrieving User Roles

Once we have the user’s ID, the key data we typically want to access are the roles assigned to that user account. WordPress includes functions for getting all roles for a user as well as checking for specific roles.

Function to Get All Roles

To retrieve an array of all the roles assigned to a user account, we can use the aptly named get_userdata() function:

$user_data = get_userdata($user_id);
$user_roles = $user_data->roles;

By passing in the user ID, get_userdata() returns an object containing information on that user including name, email, URL, registration date, etc.

Importantly for checking roles and capabilities it includes a roles array containing all the user’s roles.

Some key points on get_userdata():

  • Defined in wp-includes/pluggable.php
  • Accepts user ID as input parameter
  • Returns stdClass object containing full user data
  • roles property contains array of role names

So with get_userdata() we can easily get all the roles assigned to any user with just their ID.

Checking for a Specific Role

In some cases you may only need to check if a user has a specific role like Editor, Administrator, or a custom role.

Rather than get all the roles with get_userdata(), we can simplify the check with:

if(user_can($user_id, 'editor')) {
  // User has editor role
}

The user_can() function checks if the user ID passed has the provided role. This returns a simple true / false if the user has that role or not.

Some key points on user_can():

  • Defined in wp-includes/pluggable.php
  • Accepts user ID and role name as parameters
  • Checks if user has matching role
  • Returns boolean true or false
  • Case-sensitive role names

So user_can() allows easy checks if a user has a specific role without needing to get all roles.

Checking User Capabilities

In addition to user roles, WordPress manages a robust set of capabilities that can be assigned to roles and users. Capabilities provide finer-grained permissions and access checks for publishing content, managing plugins, modifying themes, and much more.

Getting All Capabilities

To retrieve the full array of a user’s active capabilities, we can use the wp_get_current_user() function:

$current_user = wp_get_current_user();
$user_caps = $current_user->allcaps;

This returns a WP_User object containing information on the currently logged in user.

Within that lies the allcaps property which contains key value pairs of all the capabilities granted to the user.

Some key points on wp_get_current_user():

  • Defined in wp-includes/pluggable.php
  • Returns WP_User object for logged in user
  • Contains roles, ID, email, name, and other user data
  • allcaps contains full array of granted capabilities

So with wp_get_current_user() and allcaps, developers can access the full set of capabilities available to any given user.

Checking a Capability

More commonly, plugins and themes need to check if the current user has access to a single capability rather than retrieving them all.

WordPress offers an easy current_user_can() function just for this purpose:

if(current_user_can('edit_posts')) {
  // User can edit posts
}

This function accepts the name of the capability to check and returns a boolean indicating if the current user has access or not.

Some key points on current_user_can():

  • Defined in wp-includes/pluggable.php
  • Checks a capability against the current logged in user
  • Returns true / false boolean
  • Useful for restricting access and features

So when needing to conditionally show content or enable functionality based on a capability, current_user_can() provides an easy check.

Putting It All Together

By combining user ID lookup, role checks, and capability checks, plugins and themes can create customized experiences based on the current user.

Example Function to Check Role and Capability

Here is an example function putting these together to check both role and capability:

function user_access_check() {

  $user_id = get_current_user_id();

  if(user_can($user_id,'administrator')) {
    return true; 
  }

  if(current_user_can('manage_options')) {
     return true;
  }

  return false;

}

This checks if the user either has the Administrator role OR the manage_options capability and returns true if either check passes.

This demonstrates how capabilities can provide additional flexibility by assigning them to other roles and users when simple role checks are not sufficiently granular.

Usage in Conditional Statements

We can then use this function to conditionally show or hide functionality:

if(user_access_check()) {
  // Show admin dashboard
} else {
  // Do not show dashboard
}

So by centralizing the role and capability checks into a reusable function, we can cleanly integrate permission checks within our plugins and themes.

This helps restrict access only to qualified users and avoids showing unavailable functionality to users without sufficient permissions.

Additional Context and Best Practices

When checking user roles and capabilities, some additional best practices help improve security, performance, accuracy, and maintainability in using these techniques.

Caching Lookup Results

Looking up user data and permissions can incur overhead with multiple database queries. Caching these checks avoids running the lookups as frequently.

Two options to consider:

  • Object caching via persistent cache plugins
  • Transients for temporary caching during a page load

This helps improve site performance particularly on administrative and high capability pages that make extensive access control checks.

Securing Checks

Logging user access checks and denials can shed light on suspicious or malicious activity. Additionally, performing checks server-side is more secure than relying solely on client-side code.

Some key security principles:

  • Server-side role checks using functions covered
  • Fail securely by defaulting to denying access
  • Log access failures to identify break-in attempts
  • Schedule periodic access check reviews

Plugins for Advanced Management

As site complexity increases with additional custom post types, taxonomies, plugins and complex user access controls, manually managing roles and capabilities becomes challenging.

Role and permission management plugins help fill this need including:

  • Members by Justin Tadlock
  • User Role Editor by Nsp Code
  • Capability Manager Enhanced

These plugins provide advanced interfaces and tools to assign granular access controls across all WordPress content types.

Leave a Reply

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