Show Content to Specific Roles
Adds a [show_to] shortcode that reveals the text inside it only to users with the roles you list, such as editors or customers.
Opens WPIDE on
Code
add_shortcode( 'show_to', function ( $atts, $content = '' ) {
$atts = shortcode_atts( array( 'roles' => '' ), $atts, 'show_to' );
if ( ! is_user_logged_in() ) {
return '';
}
$allowed = array_filter( array_map( 'trim', explode( ',', strtolower( $atts['roles'] ) ) ) );
$user = wp_get_current_user();
if ( ! array_intersect( $allowed, (array) $user->roles ) ) {
return '';
}
return do_shortcode( (string) $content );
} );
Notes
Example: [show_to roles="editor,administrator"]Internal note[/show_to]. Content stays hidden from everyone else, including guests.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.