50% discount on BricksLabs Pro Membership Lifetime Access. Use coupon: GOBRICKS

Conditional Rendering for Logged in/out Users by CSS Classes in Bricks

This tutorial shows how Bricks builder‘s bricks/element/render filter can be used to conditionally output elements having a class of logged-in to logged-in users only and elements having a class of logged-out to visitors that are not logged in.

Add the following in child theme’s functions.php or in a code snippets plugin:

add_filter( 'bricks/element/render', function( $render, $element ) {
	// Get the element CSS classes
	$classes = ! empty( $element->attributes['_root']['class'] ) ? $element->attributes['_root']['class'] : false;
  
	// Check if the element has the special class "logged-in"
	if ( $classes && in_array( 'logged-in', $classes ) ) {
		return is_user_logged_in();
	}
	
	// Check if the element has the special class "logged-out"
	if ( $classes && in_array( 'logged-out', $classes ) ) {
		return ! is_user_logged_in();
	}

	return $render;
}, 10, 2 );

With this in place, for any element that you wish to be output only for users that are logged into your Bricks WordPress site, simply add this class: logged-in

For any element that should be output only for visitors that are not logged in, add this class: logged-out

Sample use case: Render separate menus for logged-in users and logged-out visitors.

Reference

https://academy.bricksbuilder.io/article/filter-bricks-element-render/

Leave the first comment