Halloween Sale 15% off Ends in See the plans
PHP

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}.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.