【问题标题】:Wordpress ACF Repeater Field - Only pull in first 2 fieldsWordpress ACF 中继器字段 - 仅拉入前 2 个字段
【发布时间】:2017-03-17 16:16:07
【问题描述】:

主题有点说明一切。我只需要拉入 ACF 转发器字段的前两个字段。

这是我正在尝试使用的,但显然不正确:

<?php $args = [ 'posts_per_page' => 2, 'order' => 'desc']; ?>
<?php $ar = new WP_Query( $args ); ?>

<?php if( $ar->have_rows('prodImgs') ): while ( $ar->have_rows('prodImgs') ) : $ar->the_row(); ?>

    <img src="<?php the_sub_field('prodImg'); ?>" alt="">

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

我该怎么做?

【问题讨论】:

  • 您要显示哪些字段?当您说您只想要前 2 个字段时,这是否意味着转发器的前两行?

标签: wordpress repeater advanced-custom-fields


【解决方案1】:
<?php
// check if the repeater has data
if( have_rows('prodImgs') ) {
  //counter
  $i=0;
  //loop through the rows
  while( have_rows('prodImgs') ) {
  the_row();
  //check if 2 subfields have been shown
  if ( $i > 1 ) { break; }
  echo "<img src='" . get_sub_field('prodImg_sub') . "' alt='Lorem ipsum'>";
  $i++;
  }
}
?>

您正在混合苹果和梨、WP_Query 和 ACF 中继器字段。 WP_Query 返回帖子数据,而 ACF 函数 have_rows( $repeater_field_name, $post_id ); 检查您的页面/帖子上的自定义字段转发器中是否有任何数据(或者您是否在相关帖子/页面上指定了 $post_id)。更多信息https://www.advancedcustomfields.com/resources/repeater/

【讨论】:

    【解决方案2】:

    <?php $rows = get_field('prodImgs'); ?>
    
    <?php $i = 0; if ($rows):?>
    
        <?php foreach($rows as $row): ?>
    
            <img src="<?php echo $rows[$i][/* name of first field */]; ?>" alt="">
            <?php echo $rows[$i][/* name of Second field */]; ?>
    
        <?php $i++; endforeach; ?>
    
    <?php endif; ?>

    【讨论】:

      猜你喜欢
      • 2019-03-30
      • 2018-08-15
      • 2019-10-16
      • 2017-01-01
      • 2020-04-25
      • 2021-04-16
      • 2022-11-10
      • 1970-01-01
      • 2018-04-11
      相关资源
      最近更新 更多