Manual Theme Integration
Manual Theme Integration
If you prefer not to use a plugin, you can integrate this functionality directly into your active WordPress theme. This approach allows you to display the current user's role anywhere shortcodes are supported.
Prerequisites
- Backup your site: Before editing theme files, ensure you have a recent backup.
- Use a Child Theme: It is strongly recommended to add this code to a Child Theme. If you add it to a parent theme, your changes will be overwritten when the theme updates.
Step 1: Copy the Snippet
Open the app.php file in this repository and copy the entire PHP code block. The code primarily registers a new WordPress shortcode using the add_shortcode function.
Step 2: Edit functions.php
- Log in to your WordPress server via FTP/SFTP or use the Theme File Editor in the WordPress dashboard (Appearance > Theme File Editor).
- In the right-hand sidebar, locate and select the
functions.phpfile of your active (child) theme. - Scroll to the bottom of the file.
Step 3: Paste and Save
Paste the code from app.php at the very end of your functions.php file. If your file ends with a closing PHP tag ?>, ensure you paste the code before that tag.
// Example of what the integration looks like in functions.php
function wpb_get_current_user_role() {
if( is_user_logged_in() ) {
$user = wp_get_current_user();
$roles = ( array ) $user->roles;
return $roles[0]; // Returns the primary role
} else {
return 'Guest';
}
}
add_shortcode('user_role', 'wpb_get_current_user_role');
- Click Update File or save and upload via FTP.
Usage
Once the code is integrated into your theme, you can display the user role on any page, post, or widget area using the following shortcode:
[user_role]
Examples
- In the Block Editor: Add a "Shortcode" block and enter
[user_role]. - In Theme Template Files: If you want to hardcode the role display into a PHP template (like
header.php), use thedo_shortcodefunction:
<?php echo "Your current role is: " . do_shortcode('[user_role]'); ?>
Output Behavior
- Logged-in Users: Displays the primary role assigned to the user (e.g.,
administrator,editor,subscriber). - Logged-out Users: Displays "Guest" (or the fallback defined in the snippet).