Shortcode Usage
Overview
The primary feature of this snippet is the [user_role] shortcode. This shortcode dynamically retrieves the WordPress role of the currently logged-in user and displays it as plain text on the frontend. If a guest (non-logged-in user) visits the page, the shortcode will return an empty string by default.
Basic Usage
To display the current user's role, insert the following shortcode into any content area:
[user_role]
In the Block Editor (Gutenberg)
- Open the Page or Post editor.
- Click the + icon to add a new block.
- Search for the Shortcode block.
- Type
[user_role]into the text field. - Save or Update the page.
In the Classic Editor
- Open the Post or Page editor.
- Switch to the Visual or Text tab.
- Paste
[user_role]directly into the content area where you want the role to appear.
In Widgets
You can display the user role in sidebars or footers:
- Navigate to Appearance > Widgets.
- Add a Shortcode block or a Text widget to your desired sidebar.
- Enter
[user_role]and save.
Technical Examples
Usage within Text
You can wrap the shortcode with your own text to create personalized messages:
You are currently logged in as: [user_role]
Expected Output: "You are currently logged in as: administrator"
Using in PHP Templates
If you are a developer and need to display the user role directly within your theme's template files (e.g., header.php or author.php), use the do_shortcode function:
<?php echo do_shortcode('[user_role]'); ?>
Output Details
- Output Type: String.
- Case Sensitivity: The role slug is typically returned in lowercase (e.g.,
administrator,editor,subscriber,author), as defined by WordPress core. - Empty State: If the visitor is not logged in, the shortcode produces no visible output, ensuring the layout remains clean for guest users.