Search code examples
phpwordpressadvanced-custom-fieldsacfpro

Wordpress ACF repeater not looping when returning values


For some reason, my loop will only display the first row from the repeater. How can I get the loop to create links for all rows that have been added?

function related_pages_shortcode2() {
    if( have_rows('related_pages') ):
    while( have_rows('related_pages') ): the_row(); 

    $type = get_sub_field('type');
    $name = get_sub_field('name');
    $link = get_sub_field('url');

    $related_page = '<strong>' . $type . ': </strong>' . '<a href="' . $link . '">' . $name . '</a>';

    return $related_page;

    endwhile;

else :

endif;
}

add_shortcode( 'related_pages2', 'related_pages_shortcode2' );

Solution

  • You are returning in your function (preventing the function's further execution) instead of saving the previous output and appending new rows to it. Change your function like that so it also saves previous content generated in the while loop:

        if( have_rows('related_pages') ):
            $output = ''; // initialize the output buffer as an empty string
            while( have_rows('related_pages') ): the_row(); 
    
                $type = get_sub_field('type');
                $name = get_sub_field('name');
                $link = get_sub_field('url');
    
                $related_page = '<strong>' . $type . ': </strong>' . '<a href="' . $link . '">' . $name . '</a>';
    
                $output .= $related_page; // in this way you append the new row to the previous output
    
            endwhile;
    
        endif;