2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[WordPress]各投稿タイプ最新1件を取得する

Posted at

[WordPress]各カテゴリー最新1件の投稿を取得する
って記事を書いているときに
そういえば昔投稿タイプで似たようなことやったな〜
って思い出してまだQiitaに残してなかったので残す。

gistには残していたけど
最新の投稿のつけあわせをpost_dateでやってたんでIDでするようにした。
通常運営ならpost_dateで問題ないと思うけども
処理で一度に大量の投稿つくったりコピーしたりするとあれなんで。

ちなみに元々参考にしていた記事は
Show latest Posts from each Post Type

$query = <<<SQL
SELECT tmp.ID, tmp.post_type, tmp.post_date FROM
	(
		SELECT ID, post_type, max(post_date) AS pd FROM wp_posts
			WHERE post_status = %s
				AND post_type IN (%s, %s)
			GROUP BY post_type
	) AS post
INNER JOIN wp_posts AS tmp
   	ON tmp.post_type = post.post_type
	AND tmp.ID = post.ID
ORDER BY post.pd DESC
SQL;

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

これで投稿IDと投稿タイプと公開日が取れるので
あとはよろしくやってほしい。

2
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?