ワードプレスで特定の投稿IDを持つ投稿データだけを取得するPHPコードをご紹介いたします。

任意の投稿IDリストから投稿データを取得
任意の投稿IDのリストから投稿データを取得するコードは下記のようになります。
$post_ids = array(1,2,3);
$post_query = new WP_Query(array('post_type' => 'post','post__in' => $post_ids,'posts_per_page' => -1));
上記コードでは投稿ID1,2,3の投稿のデータをWP_Queryを使用して取得します。
‘post_type’ => ‘post’は「投稿」を示します。
‘post__in’に投稿IDの配列を渡すとその配列の投稿のみを取得できます。
‘posts_per_page’ => -1 は無制限の数を取得するという意味になります。
取得した投稿のデータを処理する
見つかった投稿の数は下記のコードで取得できます。
$found_number = $post_query->found_posts;
見つかった投稿そのもののデータは下記のようなコードで取得できます。
$found_posts = $post_query->posts;
$found_postsには下記のような構造でデータが入ります
array
0 =>
object(WP_Post)[30050]
public 'ID' => int 1
public 'post_author' => string '1' (length=1)
public 'post_date' => string '2024-08-14 15:10:20' (length=19)
public 'post_date_gmt' => string '2024-08-14 06:10:20' (length=19)
public 'post_content' => string '投稿のコンテンツ' (length=287)
public 'post_status' => string 'publish' (length=7)
public 'comment_status' => string 'open' (length=4)
public 'ping_status' => string 'closed' (length=6)
public 'post_password' => string '' (length=0)
public 'post_name' => string '投稿のスラグ' (length=17)
public 'to_ping' => string '' (length=0)
public 'pinged' => string '' (length=0)
public 'post_modified' => string '2024-09-17 14:07:55' (length=19)
public 'post_modified_gmt' => string '2024-09-17 05:07:55' (length=19)
public 'post_content_filtered' => string '' (length=0)
public 'post_parent' => int 0
public 'guid' => string 'http://****&p=16429' (length=54)
public 'menu_order' => int 0
public 'post_type' => string 'listing' (length=7)
public 'post_mime_type' => string '' (length=0)
public 'comment_count' => string '2' (length=1)
public 'filter' => string 'raw' (length=3)
1 =>
object(WP_Post)[30049]
public 'ID' => int 2
public 'post_author' => string '1' (length=1)
...
このデータはオブジェクト配列ですので下記のようなコードで次から次にデータを出力したりすることが可能です。
foreach ( $found_posts as $post ) {
echo "投稿のID".$post->ID;
echo "投稿のコンテンツ".$post->post_content;
}
WordPress ワードプレスのテーマやプラグインのカスタマイズコーディングのご依頼・ご相談はWPドクターまでお気軽にお送りください




