acf_get_field_post()


WordPressのacf_get_field_post()関数は、Advanced Custom Fields(ACF)プラグインで使用される関数で、特定のフィールドに関連付けられた投稿オブジェクトを取得するために使用されます。

構文

acf_get_field_post( $field, $post_id = false );

引数の説明:

  • $field (mixed) — フィールドのキー、ID、または名前を指定します。
  • $post_id (int|string) — 投稿IDを指定します。デフォルトは現在の投稿です。

例1: フィールドに関連付けられた投稿オブジェクトを取得

この例では、特定のフィールドに関連付けられた投稿オブジェクトを取得します。

$field_post = acf_get_field_post('field_12345'); if($field_post){ echo $field_post->post_title; }

例2: 現在の投稿のフィールドに関連付けられた投稿オブジェクトを取得

この例では、現在の投稿のフィールドに関連付けられた投稿オブジェクトを取得します。

$field_post = acf_get_field_post('field_12345', get_the_ID()); if($field_post){ echo $field_post->post_content; }

例3: カスタムフィールドの投稿オブジェクトを取得してリンクを作成

この例では、フィールドに関連付けられた投稿オブジェクトを取得し、その投稿へのリンクを作成します。

$field_post = acf_get_field_post('field_12345'); if($field_post){ echo '<a href="'.get_permalink($field_post->ID).'">'.$field_post->post_title.'</a>'; }

例4: フィールドに関連付けられた投稿のサムネイルを表示

この例では、フィールドに関連付けられた投稿のサムネイルを表示します。

$field_post = acf_get_field_post('field_12345'); if($field_post){ echo get_the_post_thumbnail($field_post->ID, 'thumbnail'); }

例5: フィールドに関連付けられた投稿のカスタムフィールドを取得

この例では、フィールドに関連付けられた投稿のカスタムフィールドを取得します。

$field_post = acf_get_field_post('field_12345'); if($field_post){ echo get_field('custom_field_name', $field_post->ID); }

例6: フィールドに関連付けられた投稿のタクソノミーを取得

この例では、フィールドに関連付けられた投稿のタクソノミーを取得します。

$field_post = acf_get_field_post('field_12345'); if($field_post){ $terms = get_the_terms($field_post->ID, 'category'); if($terms){ foreach($terms as $term){ echo $term->name; } } }

例7: フィールドに関連付けられた投稿のメタデータを取得

この例では、フィールドに関連付けられた投稿のメタデータを取得します。

$field_post = acf_get_field_post('field_12345'); if($field_post){ echo get_post_meta($field_post->ID, 'meta_key', true); }

例8: フィールドに関連付けられた投稿のコメントを取得

この例では、フィールドに関連付けられた投稿のコメントを取得します。

$field_post = acf_get_field_post('field_12345'); if($field_post){ $comments = get_comments(array('post_id' => $field_post->ID)); foreach($comments as $comment){ echo $comment->comment_content; } }

注意点

  • フィールドが存在しない場合、関数はfalseを返します。
  • 投稿IDを指定しない場合、現在の投稿が使用されます。
  • フィールドに関連付けられた投稿が存在しない場合、関数はfalseを返します。