概要
the_sub_field
関数は、Advanced Custom Fields (ACF)プラグインの一部であり、特定のサブフィールドの値を表示します。この関数は、リピーターやフレキシブルコンテンツのフィールド内で、各サブフィールドのデータを取り出す際に使用されます。主に以下のようなシナリオで利用されます。
- リピーターフィールド内のデータを表示する。
- フレキシブルコンテンツフィールドから特定のサブフィールドを取得する。
- 項目ごとの詳細情報を表示する際に使用する。
- プロジェクトや作品のリストを作成する場合。
- 特定の条件に基づいたコンテンツの表示を行う際。
- 複数のサブフィールドから動的なコンテンツを構築する。
この関数は、ACF v5以降で使用可能で、WordPressバージョンは4.0以上が推奨されます。
構文
the_sub_field($sub_field_key);
パラメータ
$sub_field_key
: 取得したいサブフィールドのキーまたは名前を指定します。
戻り値
この関数は、サブフィールドで指定された値を表示します。それ自体は値を返さず、出力のみを行います。
サンプルコード
サンプルコード1
<?php if( have_rows('team_members') ): ?>
<ul>
<?php while( have_rows('team_members') ): the_row(); ?>
<li><?php the_sub_field('member_name'); ?></li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
このコードは、リピーターフィールド「team_members」内のメンバー名をリスト形式で表示します。
サンプルコード2
<?php if( have_rows('projects') ): ?>
<div class="projects">
<?php while( have_rows('projects') ): the_row(); ?>
<h2><?php the_sub_field('project_title'); ?></h2>
<p><?php the_sub_field('project_description'); ?></p>
<?php endwhile; ?>
</div>
<?php endif; ?>
このコードは「projects」リピーターフィールドを使用して、各プロジェクトのタイトルと説明を出力します。
サンプルコード3
<?php if( have_rows('content_sections') ): ?>
<div class="content-sections">
<?php while( have_rows('content_sections') ): the_row(); ?>
<h3><?php the_sub_field('section_heading'); ?></h3>
<div><?php the_sub_field('section_content'); ?></div>
<?php endwhile; ?>
</div>
<?php endif; ?>
このコードは、任意のコンテンツセクションから見出しとコンテンツを表示するために使用されます。
サンプルコード4
<?php if( have_rows('testimonial') ): ?>
<div class="testimonials">
<?php while( have_rows('testimonial') ): the_row(); ?>
<blockquote>
"<?php the_sub_field('quote'); ?>"
<footer><?php the_sub_field('author'); ?></footer>
</blockquote>
<?php endwhile; ?>
</div>
<?php endif; ?>
このコードは、顧客のテストモニアルをブロック引用形式で表示します。引用と著者名が出力されます。
サンプルコード5
<?php if( have_rows('faq') ): ?>
<div class="faq">
<?php while( have_rows('faq') ): the_row(); ?>
<div class="faq-item">
<h4><?php the_sub_field('question'); ?></h4>
<p><?php the_sub_field('answer'); ?></p>
</div>
<?php endwhile; ?>
</div>
<?php endif; ?>
このコードは、FAQセクションを作成し、質問と回答のペアを表示します。
この関数のアクションでの使用可能性
アクション | 使用可能性 |
---|---|
mu_plugin_loaded | |
registered_post_type | |
plugins_loaded | |
wp_roles_init | |
setup_theme | |
after_setup_theme | |
set_current_user | |
init | |
register_sidebar | |
wp_loaded | |
send_headers | |
parse_query | |
pre_get_posts | |
wp | |
template_redirect | |
get_header | |
wp_head |