Conditional Rendering in Bricks Based on CSS Class

Updated on 19 Jun 2024

A user asks:

Is there a way to apply the same conditions to several elements like we set styles appending a CSS class?

I have a button with class .btn-accent with dynamic condition to check if a function is equal to 1.
I'd like to set this same visibility conditions to other elements with same class.

Bricks has a great filter hook called bricks/element/render that can be used to programmatically control the rendering (output) of elements.

CSS class-based rendering is provided in example #2 on the above page.

This Pro tutorial provides another example of using the bricks/element/render filter to output any element having a class of render-if-status-is-checked only if a "Status" True / False type of custom field is checked on an ACF Options page.

After implementing the tutorial, to output an element based on the Options page field value all you have to do is assign the CSS class to the element. You are going to tell Bricks to check the list of classes for the elements before it renders the elements and if the CSS class name you specify is present for an element then it is going to run a function that returns a true or false. If it receives true, then the element is rendered. Otherwise, it won't.

This is easier and quicker than using the Conditions dialog if you have a number of elements on which the condition should be applied.

Step 1

Install and activate ACF Pro.

Go to ACF → Options Pages.

Add a new Options Page.

Step 2

Create a field group having a True / False field attached to the above Options page.

In the Presentation tab for the field, you may want to toggle "Stylized UI" on.

Step 3

Click on Site Settings menu in the left admin menu.

Turn on the Status (technically speaking, it is a checkbox - so you are actually ticking it).

Click Update.

Step 4

Back in child theme's functions.php or your code snippets plugin, add:

This is a BricksLabs Pro tutorial.

For full access login below or create your BricksLabs Pro account

Instant access to 390+ Bricks code tutorials with BricksLabs Pro