Direct PHP Implementation
Direct PHP Implementation
While the [user_role] shortcode is convenient for use within the WordPress block editor or page builders, you may need to display the user role directly within your theme's template files (such as header.php, author.php, or sidebar.php).
Using the Function in Templates
To output the current user's role directly in your PHP templates, call the wp_show_user_role() function. Since the function returns the role as a string, you must use echo to render it.
<?php
// Display the current user's role
if ( function_exists( 'wp_show_user_role' ) ) {
echo '<span class="user-role">' . wp_show_user_role() . '</span>';
}
?>
Conditional Logic Based on Roles
You can use the return value of the function to perform conditional checks within your theme logic. This is useful for displaying specific UI elements to certain user types.
<?php
if ( function_exists( 'wp_show_user_role' ) ) {
$current_role = wp_show_user_role();
if ( 'administrator' === $current_role ) {
echo "Welcome, Admin. Access the dashboard <a href='/wp-admin'>here</a>.";
} elseif ( 'subscriber' === $current_role ) {
echo "Thank you for being a member!";
}
}
?>
Execution via do_shortcode
If you prefer to use the WordPress shortcode API within your PHP files, you can use the standard do_shortcode() function. This is less performant than calling the function directly but maintains consistency with content-area usage.
<?php echo do_shortcode( '[user_role]' ); ?>
Technical Notes
- Return Type:
string|void - Output: Returns the name of the role (e.g.,
administrator,editor,author). Returns nothing if the user is not logged in. - Dependency: Ensure the code from
app.phphas been successfully added to yourfunctions.phpfile, or the function call will result in a fatal error. Always wrap the call in afunction_exists()check for safety.