PHP Template Usage
PHP Template Usage
If you need to display the user's role programmatically within your WordPress theme files (such as header.php, sidebar.php, or a custom page template), you can use the standard WordPress do_shortcode function.
Basic Implementation
To output the current user's role anywhere in your template files, wrap the shortcode in the do_shortcode() function and use echo:
<?php echo do_shortcode('[user_role]'); ?>
Conditional Usage (Recommended)
In most cases, you only want to display the role if a user is actually logged in. You can wrap the call in a conditional check to avoid empty output or layout shifts for logged-out 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 in a Variable
If you need to process the role string further (e.g., for conditional logic or concatenating with other strings) before displaying it, you can store the output in a variable:
<?php
$current_user_role = do_shortcode('[user_role]');
// Example: Use the role in an HTML attribute
echo '<div class="user-profile" data-role="' . esc_attr($current_user_role) . '">';
echo 'Welcome, your role is ' . $current_user_role;
echo '</div>';
?>
Usage Tips
- Escaping: The shortcode already returns a string. If you are using it inside HTML attributes, always use
esc_attr()as shown in the example above. - Placement: Common files for this snippet include
author.php(to show roles on profile pages) orheader.php(to show roles in a utility navigation bar).