反向 ACF 灵活内容循环

Reverse ACF Flexible content Loop

我正在使用高级自定义字段灵活的内容,我想知道如何在 php 中反转这个循环,所以最新的文章在最上面。就像 wordpress 中的帖子一样。谢谢!

<?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; ?>

我能想到两个解决方案。

  1. get_field('article_content') 存储在一个数组上,通过访问数组中的数据而不是使用 ACF 函数来反转它并显示行。

  2. ob_start()ob_get_contents()ob_end_clean()将每一行的html存入一个数组,然后取反。我更喜欢这个解决方案,因为您可以使用 ACF 函数。

我用第二种解决方案调整了你的代码:

  <?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; ?>

代码未经测试,但我很确定它应该可以工作。

您也可以替换:

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

来自

$rows_array[] = ob_get_clean();

这是完成同一件事的更短方法。