BLOG

ブログ

  • Web制作

ACF リピーターフィールドの最後のサブフィールドだけを表示

はじめに

以前の記事で Advanced Custom Fields の最初のサブフィールドだけを表示する方法を解説しました。

今回はその逆で最後のサブフィールドだけを表示する方法です。

サンプルコード

<?php if (have_rows('repeater')) : ?>
    <?php $repeaterCount = count(get_field('repeater')); //サブフィールドの数を数える 
    ?>
    <?php $i = 1; ?>
    <?php while (have_rows('repeater')) : the_row();
        // vars
        $subField = get_sub_field('subField');
    ?>
        <?php if ($i == $repeaterCount) : ?>//最後のサブフィールドの時だけ表示
            <?php echo $subField; ?>
        <?php endif; ?>
        <?php ++$i; ?>
    <?php endwhile; ?>
<?php endif; ?>

解説

解説と言うほどでもないですが。

count関数でサブフィールドの数を数えて、最後のサブフィールドの時だけをif文で表示させています。

あまり使う場面はないかもしれませんが、先日の案件で使用したので忘れないように残しておきます。