WordPress User API
WordPress User API Integration
This snippet leverages the native WordPress User API to dynamically identify and display the role of the logged-in user. By interfacing with the WP_User object, it ensures compatibility with WordPress's built-in role and capability system.
How it Works
The script calls the wp_get_current_user() function, which retrieves the global $current_user object. It specifically accesses the roles property—an array containing all roles assigned to the user. Since most WordPress installations assign a single primary role to users, the snippet retrieves the first index of this array to return a string representation of the role (e.g., "administrator", "editor", "subscriber").
Shortcode Reference
The primary public interface for this script is the [user_role] shortcode. This can be used within the Gutenberg editor, classic editor, or inside widget areas.
Usage:
[user_role]
Output: Returns the name of the current user's role in plain text. If the user is not logged in, it will return an empty string or a null value depending on the environment context.
Programmatic Usage
While the shortcode is the intended interface for content editors, developers can also utilize the underlying logic within theme template files.
Retrieving the Role in PHP
If you need to fetch the user role programmatically within your header.php or single.php files, you can use the logic provided in the app.php file:
<?php
// Get the current user object
$current_user = wp_get_current_user();
// Check if a user is logged in and has a role
if ( !empty( $current_user->roles ) && is_array( $current_user->roles ) ) {
// Output the first role in the array
echo esc_html( $current_user->roles[0] );
}
?>
Data Types and Return Values
| Component | Type | Description |
| :--- | :--- | :--- |
| [user_role] | string | The slug of the WordPress role (e.g., author). |
| wp_get_current_user() | WP_User | The object containing user data, roles, and capabilities. |
| roles Property | array | An array of strings representing the roles assigned to the user. |
Technical Considerations
- Context: The script only returns data for the user currently viewing the page. It does not accept parameters to fetch roles for other users by ID.
- Security: The output should be treated as a string. If using the PHP logic directly, always use
esc_html()oresc_attr()to ensure the data is safe for the browser. - Role Slugs: Note that the API returns the role slug (e.g.,
administrator) rather than the role display name (e.g.,Administrator).