简体   繁体   中英

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' );

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM