the_sub_field()


WordPress関数the_sub_field()は、ACF(Advanced Custom Fields)プラグインで使用され、リピーターフィールドやフレキシブルコンテンツフィールド内の値を取得または出力するために使用されます。

構文

<?php the_sub_field( $field_name ); ?>
  • $field_name (string) — 取得または出力するサブフィールドの名前。

例1: テキストフィールドの値を出力する

リピーターフィールド内のテキストサブフィールドの値を表示します。

<?php if ( have_rows( 'repeater_field' ) ) : while ( have_rows( 'repeater_field' ) ) : the_row(); the_sub_field( 'text_field' ); endwhile; endif; ?>

例2: リンクを生成する

リピーターフィールド内のURLサブフィールドを使用してリンクを生成します。

<?php if ( have_rows( 'links_repeater' ) ) : while ( have_rows( 'links_repeater' ) ) : the_row(); echo '<a href="' . esc_url( the_sub_field( 'url_field' ) ) . '">' . the_sub_field( 'link_text' ) . '</a>'; endwhile; endif; ?>

例3: 画像を表示する

画像サブフィールドの値を取得して画像を出力します。

<?php if ( have_rows( 'gallery_repeater' ) ) : while ( have_rows( 'gallery_repeater' ) ) : the_row(); echo '<img src="' . esc_url( the_sub_field( 'image_field' ) ) . '" alt="Gallery Image">'; endwhile; endif; ?>

例4: 条件に応じてスタイルを変更する

サブフィールドの値に基づいてCSSクラスを変更します。

<?php if ( have_rows( 'style_repeater' ) ) : while ( have_rows( 'style_repeater' ) ) : the_row(); $class = the_sub_field( 'class_name' ); echo '<div class="' . esc_attr( $class ) . '">Content</div>'; endwhile; endif; ?>

例5: 数値を計算する

リピーターフィールド内の数値サブフィールドを合計します。

<?php
$total = 0;
if ( have_rows( 'numbers_repeater' ) ) : while ( have_rows( 'numbers_repeater' ) ) : the_row();
    $total += (int) the_sub_field( 'number_field' );
endwhile; endif;
echo 'Total: ' . $total;
?>

注意事項

  • the_sub_field()は、have_rows()と組み合わせて使用する必要があります。
  • サブフィールドが存在しない場合、値は空になります。
  • HTMLを出力する場合は、必ず適切なエスケープ関数を使用してください。

関連機能: