10th Aug '22
/
8 comments

How to programmatically add a class to an element in Bricks

This Pro tutorial shows how a dynamic class can be added to a query loop element in Bricks programmatically.

Let's take an example where posts of Events CPT are being shown using a query loop.

The objective is to add a class of future-event for all upcoming events that occur in the future and past-event for events that happened in the past to the element on which query loop is enabled. We can then add custom CSS to make it easy for the visitors to distinguish between past and future events.

Instead of adding a class dynamically by checking the value of the event-date custom field for each post, we could use the attributes feature and add an attribute called say, data-status and set its value to a dynamic function that returns the appropriate string (future-event or past-event). Then add the custom CSS using the [data-status="future-event"] and [data-status="past-event"] selectors.

The above approach is fine for most use cases but for whatever reason if you wish to set the date status strings as a class, your first instinct would be to use the attributes feature and add a class attribute with the value = a custom dynamic function. A potential problem with this is that the existing classes will be replaced with the class value set in the attribute.

Below is the sample code to add a hard-coded static class to each item in the loop. We will then modify it to make it dynamic.

static class
dynamic class

This is a BricksLabs Pro tutorial.

For full access login below or create your BricksLabs Pro account

Get access to all 626 Bricks code tutorials with BricksLabs Pro

Related Tutorials..

Pro
Random Row from ACF Repeater in Bricks

Random Row from ACF Repeater in Bricks

In the past, we shared how the first row of a ACF Repeater can be output in a Bricks query loop here. This Pro tutorial…
Pro
Filtering Meta Box Cloneable Group by Select Subfield for Multiple Bricks Query Loops with Conditional Output

Filtering Meta Box Cloneable Group by Select Subfield for Multiple Bricks Query Loops with Conditional Output

In the Bricks Facebook group a user asks: Consider this cloneable Meta Box field group for a Custom Post Type called Tour: with the Tour…
Pro
How to Inject a Different Type of Post in Bricks Query Loop

How to Inject a Different Type of Post in Bricks Query Loop

Updated on 26 Aug 2024 A user asks: Hello, I'd like to inject a CPT post card inside of a Bricks query loop of a different CPT…
Removing Action/Filter Inside a Plugin’s Namespaced Class Constructor

Removing Action/Filter Inside a Plugin’s Namespaced Class Constructor

Recently worked with a friend figuring out how to remove/undo/cancel an add_action() line that's inside a plugin's constructor inside a PHP Class with the file…
Categories:
Tags: