Search code examples
phpwordpressadvanced-custom-fieldsacfpro

Reverse ACF Flexible content Loop


I'am working with advanced custom fields flexible content and I wonder how to reverse this loop in php so latest article is on the top. Just like posts in wordpress. Thank you!

<?php if( have_rows('article_content') ): ?>
    <?php while( have_rows('article_content') ): the_row(); ?>

        <?php if( get_row_layout() == 'article') : ?>

            <a href="<?php the_sub_field('link'); ?>" class="article">
                <?php $att = get_sub_field('image');?>
                <?php $image = wp_get_attachment_image_src( $att, 'article-crop' ); ?>
                <img src="<?php echo $image[0]; ?>">
                <h3><?php the_sub_field('title'); ?></h3>
            </a>

        <?php elseif( get_row_layout() == 'html' ): ?>
              <?php the_sub_field('html_code'); ?>

        <?php endif; ?>
    <?php endwhile; ?>
<?php endif; ?>

Solution

  • There is two solutions i can think of.

    1. Store get_field('article_content') on an array, reverse it and display the rows by accessing data in the array instead of using ACF Functions.

    2. Use ob_start(), ob_get_contents(), ob_end_clean() to store the html of each rows in an array and reverse it. I prefer this solution because you can use ACF Functions.

    I adapted your code with the second solution :

      <?php 
     $rows_array = array();
     if( have_rows('article_content') ): ?>
            <?php while( have_rows('article_content') ): the_row(); 
              ob_start();
            ?>
    
            <?php if( get_row_layout() == 'article') : ?>
    
                <a href="<?php the_sub_field('link'); ?>" class="article">
                    <?php $att = get_sub_field('image');?>
                    <?php $image = wp_get_attachment_image_src( $att, 'article-crop' ); ?>
                    <img src="<?php echo $image[0]; ?>">
                    <h3><?php the_sub_field('title'); ?></h3>
                </a>
    
            <?php elseif( get_row_layout() == 'html' ): ?>
                  <?php the_sub_field('html_code'); ?>
    
            <?php endif; ?>
        <?php 
           $rows_array[] = ob_get_contents();
           ob_end_clean(); 
           endwhile; 
        ?>
     <?php 
       $rows_reversed_array = array_reverse($rows_array);
       echo implode('', $rows_reversed_array);
     ?>
    <?php endif; ?>
    

    Code not tested but i'm pretty sure it should work.

    You also can replace :

    $rows_array[] = ob_get_contents();
    ob_end_clean(); 
    

    by

    $rows_array[] = ob_get_clean();
    

    It's a shorter way to do the same thing.