概要
get_field
関数は、Advanced Custom Fields (ACF) プラグインで特定のフィールドの値を返します。主にカスタムフィールドのデータを取得する際に用いられ、以下のような機能に使われます:
- 投稿やページにカスタムメタデータを追加する
- 製品情報やレビューを表示する
- カスタムレイアウトの構築
- ユーザーのプロフィール情報を表示する
- イベント情報やスケジュールを表示する
- プロジェクトやポートフォリオの詳細を管理・表示する
構文
$value = get_field( $selector, $post_id );
パラメータ
- $selector (string) : 取得したいカスタムフィールドの名前。
- $post_id (int|string) : オプション。特定の投稿のID。指定しない場合は現在の投稿が使用される。
戻り値
- カスタムフィールドの値。値が存在しない場合は
null
を返します。
使用可能なACFのバージョン
- ACF 5.0 以降
使用可能なWordPressのバージョン
- WordPress 4.0 以降
この関数のアクションでの使用可能性
アクション | 使用可能性 |
---|---|
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: 投稿タイトルの下にカスタムフィールドを表示
このコードは、特定の投稿のカスタムフィールドの値をタイトルの下に表示します。
if ( have_posts() ) :
while ( have_posts() ) : the_post();
the_title( '<h1>', '</h1>' );
echo '<p>' . get_field('custom_field_name') . '</p>';
endwhile;
endif;
(出典: https://www.advancedcustomfields.com/resources/getting-started-with-acf/)
サンプル2: ユーザーのプロフィール情報を表示
このコードは、カスタムユーザーフィールドから情報を取得し、ユーザーのプロフィールに表示します。
$current_user = wp_get_current_user();
$profile_info = get_field('bio', 'user_' . $current_user->ID);
if ( $profile_info ) {
echo '<div class="bio">' . esc_html( $profile_info ) . '</div>';
}
(出典: https://www.advancedcustomfields.com/resources/get-field/)
サンプル3: カスタム投稿タイプのフィールドを取得
このコードは、特定のカスタム投稿タイプのフィールドから値を取得し、表示します。
$post_id = get_post( $id );
$project_details = get_field('project_details', $post_id);
if ( $project_details ) {
echo '<div class="project-details">' . esc_html( $project_details ) . '</div>';
}
(出典: https://www.advancedcustomfields.com/resources/get_field/)
サンプル4: 繰り返しフィールドの値を表示
このサンプルコードは、繰り返しフィールドから各値を取得し、リストとして表示します。
if( have_rows('repeater_field_name') ):
echo '<ul>';
while( have_rows('repeater_field_name') ) : the_row();
$sub_field_value = get_sub_field('sub_field_name');
echo '<li>' . esc_html($sub_field_value) . '</li>';
endwhile;
echo '</ul>';
endif;
(出典: https://www.advancedcustomfields.com/resources/repeater/)
サンプル5: カスタムフィールドを条件付きで表示
このコードは、特定の条件が満たされた場合にのみカスタムフィールドの値を表示します。
if ( is_single() && get_field('show_on_single') ) {
echo '<div class="custom-field">' . get_field('custom_field_name') . '</div>';
}
(出典: https://www.advancedcustomfields.com/resources/getting-started-with-acf/)