get_sub_field()


WordPress関数get_sub_field()は、Advanced Custom Fields (ACF)プラグインで繰り返しフィールドやフレキシブルコンテンツ内の特定のサブフィールドの値を取得するために使用されます。

構文

<?php get_sub_field( string $field_name ); ?>
  • $field_name (string) — サブフィールドの名前。必須。

例 1: 繰り返しフィールド内のサブフィールド値の取得

以下のコードは、繰り返しフィールド内のサブフィールド「title」の値を取得し表示します。

<?php if ( have_rows( 'repeater_field' ) ) : while ( have_rows( 'repeater_field' ) ) : the_row(); echo get_sub_field( 'title' ); endwhile; endif; ?>

例 2: フレキシブルコンテンツ内の特定のサブフィールドを表示

以下のコードは、フレキシブルコンテンツ内の「description」フィールドを取得します。

<?php if ( have_rows( 'flexible_content' ) ) : while ( have_rows( 'flexible_content' ) ) : the_row(); if ( get_row_layout() == 'layout_name' ) { echo get_sub_field( 'description' ); } endwhile; endif; ?>

例 3: 条件付き表示

特定のサブフィールドが空でない場合に値を表示します。

<?php if ( get_sub_field( 'subtitle' ) ) { echo get_sub_field( 'subtitle' ); } ?>

例 4: サブフィールドの画像を表示

画像サブフィールドを表示するコードです。

<?php $image = get_sub_field( 'image_field' ); if ( $image ) { echo '<img src="' . esc_url( $image['url'] ) . '" alt="' . esc_attr( $image['alt'] ) . '">'; } ?>

例 5: カスタムHTMLの生成

サブフィールドを利用してカスタムHTMLを生成します。

<?php if ( have_rows( 'custom_repeater' ) ) : while ( have_rows( 'custom_repeater' ) ) : the_row(); echo '<div class="custom-class">' . get_sub_field( 'custom_text' ) . '</div>'; endwhile; endif; ?>

注意事項

get_sub_field()はACFプラグインがインストールされていない場合動作しません。
必要に応じてhave_rows()でフィールドの存在を確認してください。
サブフィールド名は正確に指定する必要があります。


関連機能: