WordPressで記事IDを指定して投稿データを取得する方法を紹介します。
get_postを使用すると記事のタイトルや本文、投稿日時といった記事に関する情報が取得できます。
get_post|記事の情報を取得する
get_postは指定された記事IDのレコードをデータベースから取得します。
投稿オブジェクトを指定して、そのオブジェクトの各フィールドを無害化(サニタイズ)する場合にも使います。
使い方
1 2 3 |
<?php $data = get_post($id, $output, $filter); ?> |
パラメータ
$id | [整数 | WP_Post | null] [オプション] [初期値:null] 記事IDまたは投稿オブジェクト 省略すると現在の投稿が取得されます。 |
---|---|
$output | [定数] [オプション] [初期値:OBJECT] 戻り値の型
|
$filter | [文字列] [オプション] [初期値:’raw’] 無害化のコンテキスト
|
使用例
オブジェクト形式でデータを取得
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php // 投稿IDが10の投稿情報を取得 $post_10 = get_post(10); // 投稿IDが10の投稿タイトルを取得 $title = $post_10->post_title; // 投稿IDが10の投稿の親の投稿タイトルを取得 $title_parent = get_post($post_10->post_parent)->post_title; // インラインJavascript用にエスケープ処理された投稿IDが10の投稿本文を取得 $post_content = get_post($post_10, OBJECT, 'js')->post_content; ?> |
連想配列形式でデータを取得
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php // 投稿IDが10の投稿情報を取得 $post_10 = get_post(10, ARRAY_A); // 投稿IDが10の投稿タイトルを取得 $title = $post_10['post_title']; // 投稿IDが10の投稿の親の投稿タイトルを取得 $title_parent = get_post($post_10['post_parent'], ARRAY_A)['post_title']; // インラインJavascript用にエスケープ処理されたIDが投稿10の投稿本文を取得 $post_content = get_post($post_10, ARRAY_A, 'js')['post_content']; ?> |
戻り値
[WP_Post | 配列 | null]
$outputにOBJECTを指定するとWP_Postオブジェクト、ARRAY_*を指定すると配列が返されます。
指定された記事IDが存在しない場合やエラーが発生した場合にはnullが返ります。
戻り値のフィールドは以下の通りです。
ID | [整数] 投稿ID |
---|---|
post_author | [整数] 投稿者ID |
post_date | [文字列] 投稿日時 ( YYYY-MM-DD HH:MM:SS ) |
post_date_gmt | [文字列] GMTでの投稿日時 ( YYYY-MM-DD HH:MM:SS ) |
post_content | [文字列] 本文 |
post_title | [文字列] タイトル |
post_excerpt | [文字列] 抜粋 |
post_status | [文字列] 公開ステータス ( publish | pending | draft | private | static | object | attachment | inherit | future ) |
comment_status | [文字列] コメントステータス ( open | closed | registered_only ) |
ping_status | [文字列] ピンバック/トラックバックステータス ( open | closed ) |
post_password | [文字列] 閲覧パスワード |
post_name | [文字列] スラッグ |
to_ping | [文字列] ピン通知URL |
pinged | [文字列] ピン通知済みURL |
post_modified | [文字列] 更新日時 ( YYYY-MM-DD HH:MM:SS ) |
post_modified_gmt | [文字列] GMTでの更新日時 ( YYYY-MM-DD HH:MM:SS ) |
post_content_filtered | [文字列] 一時的な利用を想定された本文 通常は空。 |
post_parent | [整数] 親ID 固定ページや添付ファイルなどで使う。 |
guid | [文字列] 投稿へのリンクの書式になっている識別子 例)http://takalog.jp/?page_id=1290 |
menu_order | [整数] 固定ページの表示順序 |
post_type | [文字列] 投稿タイプ ( post | page | attachment ) |
post_mime_type | [文字列] 添付ファイルのときMIMEタイプ 例)image/png |
comment_count | [整数] コメント数 |
filter | [文字列] 無害化のコンテキスト ( raw | edit | db | display | attribute | js ) |
まとめ
get_postを使うと投稿情報が取得できますが、パーマリンクやサムネイル画像、カテゴリといった情報は含まれていません。
それらの情報を取得したい場合は別の関数を使用してください。
get_permalink|記事のパーマリンク(URL)を取得する
get_the_post_thumbnail|記事のサムネイルを取得する
get_the_category|記事のカテゴリーを取得する