WordPressで記事URLからIDを取得し、配列に入れてループを作成、任意の記事一覧を表示する方法

関連する記事などを手動でやりたい場合などに向いてるかと。
Advanced Custom FieldsでURLを記入させ、それをget_fieldで取得するのがスマートかなーと思います。

  1. 任意の記事URLからIDを取得し、配列に入れる
  2. 記事IDの配列からループを作る
  3. 最終的なコード

任意の記事URLからIDを取得し、配列に入れる

urlからIDを取得するには「url_to_postid」を使います。

<?php
//URL取得
$postURL1 = get_field('postURL1');
$postURL2 = get_field('postURL2');
$postURL3 = get_field('postURL3');

//ID取得
$postID1 = $postID2 = $postID3 = '';
if($postURL1) { $postID1 = url_to_postid($postURL1); }
if($postURL2) { $postID2 = url_to_postid($postURL2); }
if($postURL3) { $postID3 = url_to_postid($postURL3); }

//配列に入れる
$postIDs = array($postID1,$postID2,$postID3);
?>

記事IDの配列からループを作る

<?php
//クエリの作成
$args = array('post_type' =>'post', 'post__in' => $postIDs, 'orderby'=>'post__in');
$query = new WP_Query($args);

//ループの呼び出し
if($query->have_posts()): while($query->have_posts()): $query->the_post();
?>
(ループ内部)
<?php
endwhile; wp_reset_query(); endif;
?>

クエリのポイント

  • 「post__in」で配列の投稿IDを含む投稿のみに絞り込み。
  • 「'orderby'=>'post__in'」で「post__in」の配列の並び順でソート。

最終的なコード

<?php
$postURL1 = get_field('postURL1');
$postURL2 = get_field('postURL2');
$postURL3 = get_field('postURL3');
$postID1 = $postID2 = $postID3 = '';
if($postURL1) { $postID1 = url_to_postid($postURL1); }
if($postURL2) { $postID2 = url_to_postid($postURL2); }
if($postURL3) { $postID3 = url_to_postid($postURL3); }
$postIDs = array($postID1,$postID2,$postID3);
$args = array('post_type' =>'post', 'post__in' => $postIDs, 'orderby'=>'post__in');
$query = new WP_Query($args);
if($query->have_posts()): while($query->have_posts()): $query->the_post();
?>
(ループ内部)
<?php
endwhile; wp_reset_query(); endif;
?>

取得IDの数が少ないのでとりあえず羅列してますが、ID取得のあたりをfor構文にするのが最もスマートかもしれませんね。

MovableType/WordPressを使ったホームページ制作、機能追加や設置代行などの改修、システム開発、サイトの保守を手掛けております。


アナタが実現させたい機能、やりたい事をお聞かせいただけませんか? そのイメージを一緒に実現しましょう!
お問い合わせは以下のページから!!

やまライダーのサイトへ

書いた人:やまライダー(嫁)

Web屋さんで8時間フルタイム勤務をしている、いわゆるワーキングマザー。
夫婦共働きで、ムスメ氏を育てています。
主に資産運用にかかわるお金の話、ムスメ氏を育てていく上での子育ての話、そしてたまにお仕事関連の記事を書いていく予定。
プロフィールを見る