Class-based Data Attributes in Bricks

Bricks provides a bricks/element/set_root_attributes filter using which HTML classes and data attributes can be set to elements programmatically on the frontend.

If you want to add a data attribute conditionally depending on the element’s class, here’s the sample code:

add_filter( 'bricks/element/set_root_attributes', function( $attributes, $element ) {
	if ( in_array( 'test-class', $attributes['class'] ) ) {
		$attributes['data-header-type'] = 'shrinking'; 
	}

	return $attributes;
}, 10, 2 );

The above will add data-header-type attribute having a value of shrinking to any/all element(s) that have a class of test-class.

Instant access to 390+ Bricks code tutorials with BricksLabs Pro

Leave the first comment