Sub Field Value from the Last ACF Repeater Row in Bricks

A user wrote:

I am using the Bricks Extras dynamic table to pull posts out of a CPT.

These posts contain a repeater with sub-fields and I want to extract the value of a specific field in the last row.  I don’t want to loop through the rows, I just want the value of a field in the last row.

This Pro tutorial shows how we can pull the value of a specific sub field of a specific ACF Pro‘s Repeater field and output that in Bricks.

Consider an ACF Repeater called “Builders” populated on a post like this:

Now the requirement is to show the name of the last builder for this post.

After implementing the tutorial:

Step 1

Register your custom field group if you haven’t already for your post type.

Edit your posts and populate the Repeater field.

Step 2

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

<?php

/**
 * Get the value of a sub field from the last row of an ACF repeater field.
 *
 * @param string $field_name     The name of the ACF repeater field.
 * @param string $sub_field_name The name of the sub field within the repeater.
 * @return mixed|null            The value of the sub field from the last row, or null if not found.
 */
function bl_get_last_row_acf_field_value( string $field_name, string $sub_field_name ): mixed {
    $acf_rows = get_field( $field_name );

    if ( ! is_array( $acf_rows ) || empty( $acf_rows ) ) {
        return null;
    }

    $last_row = end( $acf_rows );

    return $last_row[$sub_field_name] ?? null;
}

PHP’s end() function sets the internal pointer of an array to its last element.

?? is the null coalescing operator. It checks the value and if present, returns the value and if not, returns null.

Step 3

Whitelist the bl_get_last_row_acf_field_value function.

Ex.:

<?php 

add_filter( 'bricks/code/echo_function_names', function() {
  return [
    'bl_get_last_row_acf_field_value'
  ];
} );

You should also add other functions (native or custom) being used in your Bricks instance besides bl_get_last_row_acf_field_value. This can be checked at Bricks → Settings → Custom code by clicking the Code review button.

More info on whitelisting can be found here.

Step 4

In Bricks editor to output the last row value of a sub field in a single post or in a posts query loop, use this dynamic data tag:

{echo:bl_get_last_row_acf_field_value(builders,name)}

Replace builders with the name of your Repeater field.

Replace name with the name of your sub field.