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

概要

the_field 関数は、Advanced Custom Fields (ACF) プラグインを使用して作成されたカスタムフィールドの特定のフィールドの値を表示します。この関数は主に次のような状況で使用されます。

  1. 投稿やページの追加情報を表示する場合
  2. 特定のカスタムフィールドを使ったコンテンツの構築
  3. 繰り返しフィールドの値を表示する際
  4. カスタムフィールドを使ったカスタムループの構築
  5. カスタムテンプレートでの情報表示
  6. ウィジェットやショートコードによる動的なコンテンツ生成

構文

the_field( $field_name, $post_id );

パラメータ

  • $field_name (string) – 表示したいカスタムフィールドの名前
  • $post_id (int|string) – (オプション)フィールドを取得する投稿のID。省略した場合、現在の投稿が使用される。

戻り値

この関数は値を直接出力するため、戻り値はありません。ただし、視覚的に出力された値は表示されます。

使用可能なバージョン

  • ACF のバージョン: 5.x 以上
  • WordPress のバージョン: 3.4 以上

この関数のアクションでの使用可能性

アクション 使用例
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

サンプルコード

サンプル 1

<?php
// 指定した投稿のカスタムフィールドの値を表示
the_field('custom_field_name', 42);
?>

このコードは、投稿IDが42の投稿に関連付けられたカスタムフィールド「custom_field_name」の値を表示します。

サンプル 2

<?php
// 現在の投稿のカスタムフィールドの値を表示
if( get_field('custom_field_name') ) {
    the_field('custom_field_name');
} else {
    echo '値がありません';
}
?>

このコードは、現在の投稿のカスタムフィールド「custom_field_name」が存在する場合にその値を表示し、存在しない場合は「値がありません」と表示します。

サンプル 3

<?php
// フィールドの値がある場合にスタイルを適用して表示
$value = get_field('custom_field_name');
if ($value) {
    echo '<div class="custom-field">' . esc_html($value) . '</div>';
}
?>

この例では、カスタムフィールドの値を取得し、存在する場合はCSSクラスを適用して表示しています。

サンプル 4

<?php
// 繰り返しフィールドの使用例
if( have_rows('repeater_field') ):
    while ( have_rows('repeater_field') ) : the_row();
        the_field('sub_field_name');
    endwhile;
else :
    echo '繰り返しフィールドがありません';
endif;
?>

ここでは、繰り返しフィールド「repeater_field」に含まれる各サブフィールド「sub_field_name」の値を表示しています。

サンプル 5

<?php
// フィールドの値をカスタムウィジェットとして表示
class My_Custom_Widget extends WP_Widget {
    public function widget($args, $instance) {
        echo $args['before_widget'];
        the_field('custom_field_name');
        echo $args['after_widget'];
    }
}

このコードは、カスタムウィジェット内でカスタムフィールド「custom_field_name」を表示するクラスの一部を示しています。ウィジェットの出力部分でフィールドの値を表示しています。

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


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