Conditional Logic
Conditional Logic
By default, the [user_role] shortcode displays the roles of the currently logged-in user. However, you may want to modify the snippet in your functions.php file to handle specific scenarios, such as restricting output to certain users or displaying different information based on user permissions (capabilities).
Displaying Content Based on Capabilities
Instead of simply returning the role, you can use WordPress's current_user_can() function within the snippet to add logic. This is useful if you want the shortcode to only display the role for users with specific privileges (like Administrators).
function get_current_user_role() {
// Check if the user is logged in
if ( is_user_logged_in() ) {
// Conditional: Only show the role if the user can manage options (Admin)
if ( current_user_can( 'manage_options' ) ) {
$user = wp_get_current_user();
$roles = $user->roles;
return 'Role: ' . implode(', ', $roles);
}
return 'Insufficient permissions to view role.';
}
return 'Guest';
}
add_shortcode('user_role', 'get_current_user_role');
Show Custom Text for Specific Roles
You can also use a switch or if/else statement to return friendly names for roles rather than the raw slugs (e.g., showing "Site Manager" instead of "editor").
function get_current_user_role() {
if ( !is_user_logged_in() ) return 'Logged Out';
$user = wp_get_current_user();
$role = $user->roles[0]; // Get the primary role
switch ( $role ) {
case 'administrator':
return 'System Admin';
case 'editor':
return 'Content Manager';
case 'subscriber':
return 'Member';
default:
return $role;
}
}
Usage in Template Files
If you prefer to use this logic directly in your theme's template files (like single.php or header.php) instead of a shortcode, you can call the function directly or use the global $current_user object:
<?php
$current_user = wp_get_current_user();
if ( in_array( 'author', (array) $current_user->roles ) ) {
echo 'Welcome, Author! You have contributed ' . count_user_posts($current_user->ID) . ' articles.';
}
?>
Summary of Common Capabilities
When writing your conditional logic, here are common capabilities you might use:
manage_options: Targeted at Administrators.edit_others_posts: Targeted at Editors and above.publish_posts: Targeted at Authors and above.read: Targeted at all registered users (Subscribers).