Usage in PHP Templates
Usage in PHP Templates
If you are developing a custom WordPress theme or overriding a template file, you can programmatically display the current user's role without using the WordPress editor.
Standard Implementation
To display the user role within your template files (e.g., header.php, sidebar.php, or author.php), use the do_shortcode() function:
<?php echo do_shortcode('[user_role]'); ?>
Conditional Usage
In most scenarios, user roles should only be displayed for logged-in users. You can wrap the call in the is_user_logged_in() check to prevent empty outputs or errors for guest visitors:
<?php if ( is_user_logged_in() ) : ?>
<div class="user-access-level">
<span>Current Role:</span> <?php echo do_shortcode('[user_role]'); ?>
</div>
<?php endif; ?>
Storing as a Variable
If you need to use the role value for logic further down in your template (such as applying specific CSS classes based on the role), you can return the value into a variable:
<?php
// Store the role for logic or clean output
$current_user_role = do_shortcode('[user_role]');
if ( !empty($current_user_role) ) {
echo '<span class="badge-' . esc_attr($current_user_role) . '">' . esc_html($current_user_role) . '</span>';
}
?>
Technical Notes
- Output: The snippet returns the display name of the primary role assigned to the current user.
- Context: This function relies on the WordPress global
$current_userobject. It is intended for frontend use and should be called within the WordPress environment after theinithook has fired.