This Pro tutorial provides the steps to output elements based on their CSS class to users of the specified role in WordPress when using Bricks Builder.
We shall set up two conditions:
- Elements having a class of
for-adminsto be rendered only to admins. - Elements having a class of
for-subscribersto be rendered only to subscribers.
Add the following in child theme’s functions.php or a 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 "for-admins"
if ( $classes && in_array( 'for-admins', $classes ) ) {
$user = wp_get_current_user();
$allowed_roles = array( 'administrator' );
return array_intersect( $allowed_roles, $user->roles );
}
// Check if the element has the special class "for-subscribers"
if ( $classes && in_array( 'for-subscribers', $classes ) ) {
$user = wp_get_current_user();
$allowed_roles = array( 'subscriber' );
return array_intersect( $allowed_roles, $user->roles );
}
return $render;
}, 10, 2 );
Reference
https://developer.wordpress.org/reference/functions/current_user_can/#comment-4083