Advanced Custom FieldsのアドオンRepeater Fieldの出力メモ

Advanced Custom FieldsのアドオンRepeater Fieldの出力メモ

いつも忘れやすいので・・・
リピーターフィールドを用いる際の出力設定。

■詳細ページ内で取得(独自関数使用)

<?php if( have_posts() ): ?>
<?php while( have_posts() ) : the_post(); ?>
  <?php
    $cnt   = 0;
    $post_row = get_post_meta(get_the_ID(),'post_row',true);
    while(the_repeater_field('post_row')){
      $data[$cnt]['title'] = get_sub_field('post_row_title');
      $media = get_sub_field('post_row_image');
      $data[$cnt]['image']  = $media['url'];
      $data[$cnt]['caption'] = get_sub_field('post_row_caption');
      $cnt++;
    }
  ?>
  <?php if($post_row): ?>
  <?php foreach ($data as $value) : ?>
    <?php echo $value['title']; ?>
    <img src="<?php echo $value['image']; ?>" alt="<?php if($value['caption']): ?><?php echo $value['caption']; ?><?php endif; ?>">
  <?php endforeach; ?>
  <?php endif; ?>
<?php endwhile; ?>
<?php endif; ?>

■functionなどで使用(idから取得/独自関数を使わない)

function my_custom_get_post($id) {
    $cnt   = 0;
    $post_row = get_post_meta($id,'post_row',true);
    if($post_row){
        for ($i = 0; $i < $post_row; $i++ ){
          $data[$cnt]['title'] = get_post_meta($id, 'post_row_'.$i.'_post_row_title', true);
          $media     = get_post_meta($id, 'post_row_'.$i.'_post_row_image', true);
          $temp  = wp_get_attachment_image_src($media, 'large');
          $data[$cnt]['image']   = $temp[0];
          $data[$cnt]['caption'] = get_post_meta($id, 'post_row_'.$i.'_post_row_caption', true);
          $cnt++;
      }
    }
    return $data;
}
<?php $post_row = my_custom_get_post(get_the_ID()); ?>
<?php if($post_row): ?>
<?php foreach ($data as $value) : ?>
  <?php echo $value['title']; ?>
  <img src="<?php echo $value['image']; ?>" alt="<?php if($value['caption']): ?><?php echo $value['caption']; ?><?php endif; ?>">
<?php endforeach; ?>
<?php endif; ?>