LoginSignup
2
2

More than 5 years have passed since last update.

[WordPress]各カテゴリー最新1件の投稿を取得する

Last updated at Posted at 2018-05-24

以前クライアントから表題のような仕様で
(正確には、さらにランダムかつ計50件まで)
依頼を受けた。

結局この件は、だいたいよくあるパターンだが
運用では数種類カテゴリーの記事しか更新されないので
ほとんど旧い記事が表示されるんやでっていうことで普通の仕様になった。

とはいえ、今後もこのようなわけわからん依頼がくるやもしれんので
とりあえず残すことにする。

$query = <<<SQL
SELECT WP.ID, WTT.term_id FROM wp_term_taxonomy AS WTT
    INNER JOIN wp_term_relationships AS WTR ON WTR.term_taxonomy_id = WTT.term_taxonomy_id
    INNER JOIN (SELECT ID, post_type, post_status FROM wp_posts ORDER BY post_date DESC) AS WP ON WP.ID = WTR.object_id
WHERE
    WTT.taxonomy = %s
    AND WTT.count > %d
    AND WP.post_type = %s
    AND WP.post_status = %s
GROUP BY WTT.term_taxonomy_id
ORDER BY RAND()
LIMIT 50
SQL;

global $wpdb;
$ret = $wpdb->get_results($wpdb->prepare($query, ['category', 0, 'post', 'publish']), ARRAY_A);

これで投稿IDとタームIDが取れるので
あとはよろしくやってほしい。

ちなみに投稿タイプverは下記
[WordPress]各投稿タイプ最新1件を取得する

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2