sinanisler logo

ACF Repeater, First Row First Field Value, Dynamic Tag

This code adds a dynamic tag {first_repeater_text} for bricks loop. It gets the current post acf repeater field first row text value.

Change this code according to your acf setup.

Repeater Field Group Name: immobilienportfolio-repeater-field

Repeater First Row Field Name: immobilienportfolio-repeater-text

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

    return $tags;
}

// Retrieves the first text of a repeater field associated with a post.
function get_first_repeater_text( $post ) {
    if ( $post && isset( $post->ID ) && have_rows('immobilienportfolio-repeater-field', $post->ID) ) {
        // Repeater Field Group Name, Change it for your setup
        $repeater = get_field('immobilienportfolio-repeater-field', $post->ID);
        

        if (!empty($repeater)) {
            $first_row = $repeater[0];
            // Repeater Field Name, Change it for your setup
            $first_row_text = $first_row['immobilienportfolio-repeater-text'];
            return esc_html($first_row_text);
        }
    }
    return '';
}

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

// Optionally, replace a placeholder in content with the actual first repeater text.
// This step may not be necessary if you're only using the dynamic tag in Bricks Builder directly,
// but it's here if you need it for more complex dynamic content scenarios.
add_filter( 'bricks/dynamic_data/render_content', 'render_first_repeater_text_in_content', 10, 3 );
add_filter( 'bricks/frontend/render_data', 'render_first_repeater_text_in_content', 10, 2 );
function render_first_repeater_text_in_content( $content, $post, $context = 'text' ) {
    if ( strpos( $content, '{first_repeater_text}' ) !== false ) {
        $text = get_first_repeater_text( $post );
        $content = str_replace( '{first_repeater_text}', $text, $content );
    }
    return $content;
}

Leave the first comment