Nested Meta Box Query Loop Inside a CPT Query Loop in Bricks

This Pro tutorial provides the steps for setting up a cloneable Meta Box group query inside a CPT query in Bricks.

Scenario:

CPT: course

Meta Box field for the course CPT: events of the type Group and cloneable with these sub fields: Start Datetime and End Datetime – both of the type Datetime Picker.

CPT item 1 (Course 1):

CPT item 2 (Course 2):

A static Page having the nested query loops on the front end:

Step 1

Set the Save format for your Datetime Picker fields to Y-m-d H:i:s.

Tick “Save value as timestamp”.

If your CPT entries already have the fields populated prior to making the above two changes, edit them, re-select the date and time and update.

Step 2

Edit any static Page with Bricks.

By the end of this tutorial, the structure should look like this:

Add a Section and inside its Container a “Our Courses” h2 heading.

Add a Container below the Heading.

Add a Block inside and change its name to say, “Course CPT Loop”.

Enable the query loop on it and set the Post type in query settings to Courses.

Add a h3 Post Title element inside the Block.

Add a Block below the Post Title.

Change its name to say, “Events Field Loop”.

Enable the query loop on it and set the Query to “MB Group: Events”.

Step 3

Let’s examine the structure of the inner loop’s object array during each loop iteration.

Add the following in a Code element inside the Events Field Loop:

<?php

print( '<pre>' . print_r( BricksQuery::get_loop_object(), true ) . '</pre>' );

?>

Set Execute Code on and check the builder or the front end.

You should see something like this:

For each iteration, the loop object is an array that contains two items: start_datetime and end_datetime. These are the IDs of the sub fields inside the Meta Box cloneable group field.

Both these array items are arrays themselves with these items in each: timestamp and formatted.

Therefore, if we want to grab the value of timestamp for each item, we first need to get the loop item object, then access its start_datetime or end_datetime and then, timestamp.

Define a custom function that takes a (sub) field ID and date format as its arguments and returns the date of the loop object’s field in the specified format.

Add the following in child theme‘s functions.php (w/o the opening PHP tag) or a code snippets plugin:

function bl_get_datetime_field_formatted( $field, $format = 'd M g:i a' ) {
	$loop_item_object = BricksQuery::get_loop_object();

	$timestamp = $loop_item_object[$field]['timestamp'];

	return date( $format, $timestamp );
}

Delete the Code element.

Add a Basic Text element and change its text to


{echo:bl_get_datetime_field_formatted(start_datetime)} – {echo:bl_get_datetime_field_formatted(end_datetime)}

view raw

gistfile1.txt

hosted with ❤ by GitHub

That’s it!

References

https://docs.metabox.io/fields/datetime/#template-usage

https://brickslabs.com/loop-item-id-and-loop-item-object-in-bricks/