Output First Value from Custom Repeater Field, Bricks Builder Dynamic Tag: Output First Value from Custom Repeater Field

change YOUR_FIELD_NAME_HERE

dynamic tag : {repeater_text_first}

// Adds a new tag 'repeater_text_first' to the Bricks Builder dynamic tags list.
add_filter( 'bricks/dynamic_tags_list', 'add_repeater_text_first_tag_to_builder' );
function add_repeater_text_first_tag_to_builder( $tags ) {
    $tags[] = [
        'name'  => 'repeater_text_first',
        'label' => 'Repeater Text First',
        'group' => 'Custom Data',
    ];
    return $tags;
}

// Retrieves the first text from the 'repeattext' repeater field.
function get_repeater_text_first( $post ) {
    if ( $post && isset( $post->ID ) ) {
        $repeater = get_post_meta( $post->ID, 'YOUR_FIELD_NAME_HERE', true );
        if ( !empty($repeater) && is_array($repeater) ) {
            // If each item is just a string, this works:
            $first_text = $repeater[0];
            // If it's an array with ['text' => 'value'], use $repeater[0]['text']
            return is_array($first_text) && isset($first_text['text']) ? esc_html($first_text['text']) : esc_html($first_text);
        }
    }
    return '';
}

// Renders the 'repeater_text_first' tag by fetching the first text of the repeater field.
add_filter( 'bricks/dynamic_data/render_tag', 'render_repeater_text_first_tag', 10, 3 );
function render_repeater_text_first_tag( $tag, $post, $context = 'text' ) {
    if ( $tag === 'repeater_text_first' ) {
        return get_repeater_text_first( $post );
    }
    return $tag;
}

// Optionally, replace a placeholder in content with the actual first repeater text.
add_filter( 'bricks/dynamic_data/render_content', 'render_repeater_text_first_in_content', 10, 3 );
add_filter( 'bricks/frontend/render_data', 'render_repeater_text_first_in_content', 10, 2 );
function render_repeater_text_first_in_content( $content, $post, $context = 'text' ) {
    if ( strpos( $content, '{repeater_text_first}' ) !== false ) {
        $text_first = get_repeater_text_first( $post );
        $content = str_replace( '{repeater_text_first}', $text_first, $content );
    }
    return $content;
}