Conditional Visibility
Conditional Visibility
To ensure sensitive role information is only displayed to the appropriate audience, you can implement conditional visibility logic. This allows you to restrict the [user_role] output based on the current user's permissions or specific site requirements.
Restricting via PHP (Recommended for Developers)
If you are calling the user role directly within your theme templates (e.g., header.php or author.php), wrap the execution in a WordPress capability check. This is the most secure method for handling visibility.
<?php
// Only show the user role if the visitor is logged in and can edit posts
if ( is_user_logged_in() && current_user_can( 'edit_posts' ) ) {
echo do_shortcode( '[user_role]' );
}
?>
Usage with Block Editor Conditionals
If you are using a page builder (like Elementor, Oxygen, or Zion) or the Gutenberg Block Editor with a visibility plugin, you can set "Display Conditions" on the block containing the shortcode.
- Select the Shortcode Block containing
[user_role]. - Navigate to the Advanced or Visibility settings.
- Set the logic to:
User Role->Is->Administrator(or your preferred role).
Extending the Shortcode for Permission Logic
You can modify the code you pasted into functions.php to support a capability attribute. This allows you to define visibility requirements directly within the shortcode.
Modify your snippet to include a check like this:
// Inside your shortcode function logic:
$atts = shortcode_atts( array(
'cap' => '', // Default: no capability required
), $atts );
if ( !empty( $atts['cap'] ) && !current_user_can( $atts['cap'] ) ) {
return ''; // Return nothing if the user lacks the required capability
}
Usage Example:
[user_role cap="manage_options"]
In the example above, the role will only render if the current user has the manage_options capability (typically Administrators).
Visibility Checklist
| Requirement | Implementation Method |
| :--- | :--- |
| Logged-in users only | Wrap in is_user_logged_in() check. |
| Specific Capabilities | Use current_user_can( 'capability_name' ). |
| Admin-only view | Use current_user_can( 'manage_options' ). |
| Frontend Styling | Use CSS selectors targeting the output container to hide/show based on screen size or parent classes. |