In a Bricks project I am currently working on, there are nested query loops – team members inside departments on a Page. Each team member query loop’s parent initially had these classes:
grid--4 grid--l-3 grid--m-1 list--none align-items--center
These are ACSS classes that lays out the list items in a 4-column (on desktops) grid.
When there are more than 4 team members in any row, they will wrap down to a new line in the CSS grid.
The requirement is to show the items in 5 columns if the number of team members in a department is 5 and in 6 columns if the number of team members in a department is 6.
So, based on the query result count of a Bricks query loop, the class grid--4 should either be grid--4 or grid--5 or grid--6.
If the query result count is 5, the class should be grid--5.
If the query result count is 6, the class should be grid--6.
For all other query result counts, grid--4.
This Pro tutorial provides the steps to accomplish the above based on the How to programmatically add a class to an element in Bricks tutorial.
Step 1
Add the following in child theme‘s functions.php (w/o the opening PHP tag) or a code snippets plugin:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| add_filter( ‘bricks/element/render_attributes’, function( $attributes, $key, $element ) { | |
| if ( $element->id !== ‘krzrhv’ ) { | |
| return $attributes; | |
| } | |
| // print( ‘<pre>’ . print_r( $attributes, true ) . ‘</pre>’ ); | |
| switch ( bricks_render_dynamic_data( ‘{query_results_count:qyhdev}’ ) ) { | |
| case ‘5’: | |
| $class = ‘grid–5’; | |
| break; | |
| case ‘6’: | |
| $class = ‘grid–6’; | |
| break; | |
| default: | |
| $class = ‘grid–4’; | |
| break; | |
| } | |
| array_push( $attributes[ ‘_root’ ][ ‘class’ ], $class ); | |
| return $attributes; | |
| }, 10, 3 ); |
Replace krzrhv with the Bricks ID of your query loop-enabled element’s parent.
Replace qyhdev with the Bricks ID of your query loop-enabled element.
