Installation as a Plugin
Installation as a Plugin
While adding code to your theme's functions.php file is a quick solution, packaging this tool as a standalone plugin is the recommended best practice. This ensures the shortcode continues to work even if you change your site's theme and keeps your custom logic separate from your presentation layer.
Step 1: Create the Plugin File
- On your local machine, create a new folder named
wp-show-user-role. - Inside that folder, create a new file named
wp-show-user-role.php.
Step 2: Add Plugin Headers and Code
Open the file in a text editor and add the following code. This includes the required WordPress plugin header and the logic from app.php:
<?php
/**
* Plugin Name: WP Show User Role Frontend
* Description: Displays the current user's role using a shortcode.
* Version: 1.0.0
* Author: Supervised
*/
// Prevent direct access to the file
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Logic from app.php
* Registers the [user_role] shortcode
*/
function wpsu_get_current_user_role() {
if ( is_user_logged_in() ) {
$user = wp_get_current_user();
$roles = ( array ) $user->roles;
return esc_html( reset( $roles ) ); // Returns the primary role
}
return ''; // Returns empty if the user is not logged in
}
add_shortcode( 'user_role', 'wpsu_get_current_user_role' );
Step 3: Install the Plugin
There are two ways to add this to your WordPress site:
Option A: Via FTP/SFTP
- Connect to your server using an FTP client (like FileZilla).
- Navigate to
/wp-content/plugins/. - Upload the entire
wp-show-user-rolefolder.
Option B: Via WordPress Dashboard
- Compress the
wp-show-user-rolefolder into a.zipfile. - Log in to your WordPress Admin dashboard.
- Navigate to Plugins > Add New > Upload Plugin.
- Select your
.zipfile and click Install Now.
Step 4: Activation
Once the files are uploaded, go to the Plugins menu in your WordPress dashboard and click Activate next to WP Show User Role Frontend.
Usage
After activation, you can display the current user's role anywhere on your site that supports shortcodes (Posts, Pages, or Widgets).
Shortcode
Insert the following shortcode into the Gutenberg editor or a Text widget:
[user_role]
Integration Features
- Dynamic Output: The shortcode automatically detects the logged-in user and displays their primary role (e.g., "administrator", "editor", "subscriber").
- Guest Handling: If a visitor is not logged in, the shortcode will return an empty string, ensuring no broken UI elements for public visitors.
- Security: The output is escaped using
esc_html()to prevent XSS vulnerabilities.