Skip to main content
Login Join
Snippet · PHP

Visibility by User Role — Hide blocks for guests or members.

Shared by Rashed Hossain · August 17, 2026

7 views
Back to Snippets

2 approaches to this. Compare them and pick what fits your setup.

Lightweight approach by Rashed Hossain

Here's a lightweight WordPress code snippet that lets you hide any Gutenberg block based on whether the visitor is logged in or not.

Simply add one of these CSS classes to a block:

  • hide-for-guests → Visible only to logged-in users.

  • hide-for-members → Visible only to logged-out visitors.

No plugin required.

Step 1: Add to functions.php

Step 2: Use It in Gutenberg

  1. Select any block.

  2. Open Advanced → Additional CSS class(es).

  3. Add one of these classes:

Class

Visibility

hide-for-guests

Logged-in users only

hide-for-members

Logged-out visitors only

Example

A Download Button with the class hide-for-guests will only appear for members who are logged in.

A Sign Up call-to-action with hide-for-members will only appear to visitors who haven't logged in yet.

Why this approach?

  • No extra plugin.

  • Works with any Gutenberg block.

  • Uses WordPress's render_block filter.

  • Keeps hidden content out of the rendered HTML, making it more secure than hiding it with CSS alone.


/**
 * Hide Gutenberg blocks based on user login status.
 *
 * Classes:
 * - hide-for-guests  = Only logged-in users can see it.
 * - hide-for-members = Only logged-out visitors can see it.
 */

function txwp_block_visibility_by_role( $block_content, $block ) {

	if ( empty( $block['attrs']['className'] ) ) {
		return $block_content;
	}

	$classes = $block['attrs']['className'];

	// Hide from guests.
	if ( strpos( $classes, 'hide-for-guests' ) !== false && ! is_user_logged_in() ) {
		return '';
	}

	// Hide from logged-in users.
	if ( strpos( $classes, 'hide-for-members' ) !== false && is_user_logged_in() ) {
		return '';
	}

	return $block_content;
}

add_filter( 'render_block', 'txwp_block_visibility_by_role', 10, 2 );
Know a different way to do this? Add your approach as a variation so folks can compare them side by side.
Submit a variation

0 comments