【问题标题】:Reverse ACF Flexible content Loop反向 ACF 灵活内容循环
【发布时间】:2020-07-10 15:17:35
【问题描述】:

我正在使用高级自定义字段灵活的内容,我想知道如何在 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; ?>

【问题讨论】:

  • 我看不到任何将显示此代码的帖子?它只是没有帖子关系的自定义字段。
  • 嘿亚历克西斯,是的,没有帖子。我想尊重它只是 acf 灵活的内容。

标签: php wordpress advanced-custom-fields acfpro


【解决方案1】:

我能想到两种解决方案。

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

这是做同样事情的一种更短的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-31
    • 1970-01-01
    • 2016-04-07
    • 2017-01-07
    • 2019-08-18
    • 2016-02-01
    • 2020-02-12
    • 2013-12-29
    相关资源
    最近更新 更多