get_post_field()


WordPressのget_post_field()関数は、特定の投稿やページのフィールド値を取得するために使用されます。

構文

get_post_field( string $field, int|WP_Post $post = null, string $context = 'display' );

引数の説明:

  • $field (string) — 取得したいフィールド名(例: ‘post_title’, ‘post_content’, ‘post_date’など)。
  • $post (int|WP_Post) — 投稿IDまたはWP_Postオブジェクト。省略した場合、現在の投稿が使用されます。
  • $context (string) — フィールドのコンテキスト(’display’、’edit’、’raw’など)。デフォルトは’display’。

例1: 投稿のタイトルを取得

この例では、投稿のタイトルを取得して表示します。

<?php echo get_post_field('post_title', get_the_ID()); ?>

例2: 投稿の内容を取得

この例では、投稿の内容を取得して表示します。

<?php echo get_post_field('post_content', get_the_ID()); ?>

例3: 投稿の公開日を取得

この例では、投稿の公開日を取得して表示します。

<?php echo get_post_field('post_date', get_the_ID()); ?>

例4: 投稿のスラッグを取得

この例では、投稿のスラッグを取得して表示します。

<?php echo get_post_field('post_name', get_the_ID()); ?>

例5: 投稿のステータスを取得

この例では、投稿のステータスを取得して表示します。

<?php echo get_post_field('post_status', get_the_ID()); ?>

例6: 投稿のタイプを取得

この例では、投稿のタイプを取得して表示します。

<?php echo get_post_field('post_type', get_the_ID()); ?>

例7: 投稿の著者IDを取得

この例では、投稿の著者IDを取得して表示します。

<?php echo get_post_field('post_author', get_the_ID()); ?>

例8: 投稿の抜粋を取得

この例では、投稿の抜粋を取得して表示します。

<?php echo get_post_field('post_excerpt', get_the_ID()); ?>

注意点:

  • get_post_field()は、指定されたフィールドが存在しない場合に空の文字列を返します。
  • コンテキストに’raw’を指定すると、フィルタリングされていない生のデータが返されます。
  • 投稿が存在しない場合、関数はnullを返します。

関連機能: