Theme Integration
Theme Integration
Integrating the wp-show-user-role-frontend snippet into your WordPress site allows you to display a logged-in user's role anywhere shortcodes are supported. You can implement this via your theme's functions file or by creating a lightweight custom plugin.
Method 1: Using functions.php (Recommended for Quick Setup)
The most common way to add this functionality is by appending the snippet to your active theme's functions.php file.
- Navigate to your WordPress installation directory.
- Go to
/wp-content/themes/your-active-theme/. - Open
functions.phpin a code editor. - Copy the contents of
app.phpfrom this repository and paste it at the bottom of the file:
// Add the User Role Shortcode
add_shortcode('user_role', 'get_current_user_role');
function 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'; // Returns for non-logged-in users
}
}
Note: If you are using a third-party theme, it is highly recommended to use a Child Theme. This prevents your changes from being overwritten when the parent theme is updated.
Method 2: Site-Specific Plugin (Best Practice)
If you want the functionality to persist even if you change your theme, create a site-specific plugin.
- Navigate to
/wp-content/plugins/. - Create a new folder named
wp-show-user-role. - Inside that folder, create a file named
wp-show-user-role.php. - Add the following code:
<?php
/**
* Plugin Name: WP Show User Role
* Description: Displays the current user's role via shortcode.
* Version: 1.0
*/
add_shortcode('user_role', function() {
if( is_user_logged_in() ) {
$user = wp_get_current_user();
$roles = (array) $user->roles;
return current($roles);
}
return '';
});
- Go to your WordPress Dashboard > Plugins and click Activate.
Displaying the User Role
Once the code is integrated, you can display the user role in two ways:
1. In the Block Editor or Widgets
Simply add the shortcode block or a text block and type:
[user_role]
2. In Theme Template Files (PHP)
If you are editing a theme template (like header.php or sidebar.php), use the do_shortcode function:
<?php echo 'Your role is: ' . do_shortcode('[user_role]'); ?>
Technical Details
- Hook:
add_shortcode - Tag:
user_role - Return Type:
string - Logic: The snippet fetches the
$user->rolesarray. By default, it returns the first role assigned to the user. If the user is not logged in, it returns an empty string or "Guest" depending on your custom implementation of the snippet.