プラグインAdvanced custom fields(ACF)のthe_sub_field関数の使用方法・解説

概要

the_sub_field関数は、Advanced Custom Fields (ACF)プラグインの一部であり、特定のサブフィールドの値を表示します。この関数は、リピーターやフレキシブルコンテンツのフィールド内で、各サブフィールドのデータを取り出す際に使用されます。主に以下のようなシナリオで利用されます。

  1. リピーターフィールド内のデータを表示する。
  2. フレキシブルコンテンツフィールドから特定のサブフィールドを取得する。
  3. 項目ごとの詳細情報を表示する際に使用する。
  4. プロジェクトや作品のリストを作成する場合。
  5. 特定の条件に基づいたコンテンツの表示を行う際。
  6. 複数のサブフィールドから動的なコンテンツを構築する。

この関数は、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

この関数について質問する


上の計算式の答えを入力してください