Configuring Image Gallery dynamic source in Bricks

Let’s say you have a custom field created with ACF Pro of the type Gallery called “Property Gallery” for posts of “Property” CPT.

In the Bricks single property CPT template, we can add an Image Gallery element and select our ACF field to display a grid or masonry of the selected images for each property.

Now the requirement is to randomize the order of these images and output only a specific number of them, like 3.

This Pro tutorial shows how this can be done by creating a custom function that takes a field name and the number as parameters and returns an array of image IDs. We shall use this function as the source in the Image Gallery element.

Step 1

Add the following in child theme‘s functions.php or a code snippets plugin:

<?php 

function bl_get_acf_gallery_random_ids( string $field_name, int $num = 0 ): array {
  $my_acf_images = BricksIntegrationsDynamic_DataProviders::render_tag( "{acf_$field_name}", get_the_ID(), 'image' );

  if ( ! is_array( $my_acf_images ) || empty( $my_acf_images ) ) {
    return [];
  }

  shuffle( $my_acf_images );

  return $num > 0 ? array_slice( $my_acf_images, 0, $num ) : $my_acf_images;
}

Note: If the code is being added in child theme’s functions.php near the end, do not include the opening PHP tag.

Step 2

Edit your singular template with Bricks and inside a Section’s Container, add an Image Gallery element.

Set its source to:

{echo:bl_get_acf_gallery_random_ids(property_gallery)}

Replace property_gallery with the name of your Gallery-type of ACF Pro field attached to your post type.

The above will display the images in random order.

If you want to limit the number of images, specify that number as the 2nd argument like this:

{echo:bl_get_acf_gallery_random_ids(property_gallery,3)}