(ACF)Advanced Custom Fieldsの基本設定(繰り替えし・グループ含む)
この記事では、Advanced Custom Fields (ACF) を使用してカスタムフィールドを表示する際によく使うコードをまとめています。
特に基本的な表示方法や、「繰り返しフィールド」「柔軟コンテンツ」の使い方を紹介します。
基本
「〇〇〇」はフィールド名です。
<?php if(get_field('〇〇〇')): ?>
<?php the_field('〇〇〇'); ?>
<?php endif; ?>
または短くまとめる場合:
<?php if(get_field('〇〇〇')): the_field('〇〇〇'); endif; ?>
繰り返しフィールド(PROのみ)
繰り返しフィールドを使う場合のコード例です。以下は、ul
タグ内にli
で繰り返し表示する例になります。
- 〇〇〇:フィールド名
- △△△:サブフィールド名
<?php if(get_field('〇〇〇')): ?>
<ul>
<?php while(has_sub_field('〇〇〇')): ?>
<?php if(get_sub_field('△△△')): ?>
<li>
<?php the_sub_field('△△△'); ?>
</li>
<?php endif; ?>
<?php endwhile; ?>
</ul>
<?php endif; ?>
柔軟コンテンツ(PROのみ)
- 〇〇〇:フィールド名
- ▽▽▽:レイアウト名1
- △△△:フィールド名(レイアウト内)
- ●●●:レイアウト名2
- ▼▼▼:繰り返しフィールド名(レイアウト内)
- ▲▲▲:サブフィールド名(繰り返しフィールド内)
<?php while(has_sub_field('〇〇〇')): ?>
<?php if(get_row_layout() == '▽▽▽'): ?>
<?php if(get_sub_field('△△△')): ?>
<?php the_sub_field('△△△'); ?>
<?php endif; ?>
<?php elseif(get_row_layout() == '●●●'): ?>
<?php while(have_rows('▼▼▼')): the_row(); ?>
<?php if(get_sub_field('▲▲▲')): ?>
<?php the_sub_field('▲▲▲'); ?>
<?php endif; ?>
<?php endwhile; ?>
<?php endif; ?>
<?php endwhile; ?>
これらのコードは、カスタムフィールドを効率的に扱うための基本となるスニペットです。必要に応じてコピー&ペーストしてカスタマイズしてください!