Show or Hide Blocks for Members and Guests
Hides any block from visitors or members based on a CSS class you add in the block's Advanced panel: wpide-members-only, wpide-guests-only or wpide-role-{role}.
Opens WPIDE on
Code
add_filter( 'render_block', function ( $html, $block ) {
$classes = isset( $block['attrs']['className'] ) ? preg_split( '/\s+/', (string) $block['attrs']['className'] ) : array();
if ( ! $classes || false === strpos( $block['attrs']['className'], 'wpide-' ) ) {
return $html;
}
$logged_in = is_user_logged_in();
if ( in_array( 'wpide-members-only', $classes, true ) && ! $logged_in ) {
return '';
}
if ( in_array( 'wpide-guests-only', $classes, true ) && $logged_in ) {
return '';
}
$wanted = array();
foreach ( $classes as $class ) {
if ( 0 === strpos( $class, 'wpide-role-' ) ) {
$wanted[] = substr( $class, 11 );
}
}
if ( $wanted && ! array_intersect( $wanted, $logged_in ? (array) wp_get_current_user()->roles : array() ) ) {
return '';
}
return $html;
}, 10, 2 );
Notes
Hidden blocks are removed on the server, so their content never reaches the browser. Example class for editors only: wpide-role-editor.
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.