Back Story:
One of my clients wanted to have a client portal with a bunch of pages hidden behind a custom client login. Only those clients who create a user account on her client portal will have access to the hidden pages. Basically, she wanted to restrict access to the hidden pages from the outside world.
To handle this requirement, I first created a new role called ‘subscriber’. I restricted access to the hidden pages to ONLY the ‘subscriber’ and ‘admin roles. I wanted to test out the capabilities of the user roles to make sure I have things configured correctly. Below are some of the scenarios I tested out with the code samples.
Scenario 1: List all capabilities of the currently logged-in user role.
Step 1:
Open up the template file where you want to display and test out the capabilities of the currently logged-in user role.
Step 2:
Copy the following code snippet to the template file(PHP file). Save and update the file on the server where you are viewing the page.
The PHP code snippet
$data = get_userdata( get_current_user_id() );
if ( is_object( $data) ) {
$current_user_caps = $data->allcaps;
// print it to the screen
echo '<pre>' . print_r( $current_user_caps, true ) . '</pre>';
}
Step 3:
View the page on the server(or local depending on your development setup). The above PHP code will display an array of all the capabilities assigned to the currently logged-in WordPress user role. If you’ve added any custom capabilities, they will also be included in the display.
Scenario 2: List the capabilities of all the user roles on the site.
Step 1:
Open up the template file where you want to display and test out all the capabilities and the user roles.
Step 2:
Copy the following code snippet to the template file(PHP file). Save and update the file on the server where you are viewing the page.
The PHP code snippet
global $wp_roles;
$roles = $wp_roles->roles;
// print it to the screen
echo '<pre>' . print_r( $roles, true ) . '</pre>';
Step 3:
View the page on the server(or local depending on your development setup). The above PHP code will display an array of all the user roles and the capabilities for each of the user roles. If you have created custom user roles and/or capabilities, they will also be displayed in the result.