wp_get_recent_posts() の使い方|説明・引数・注意点

説明

wp_get_recent_posts() は、最近の投稿を配列で取得する関数です。

基本構文

wp_get_recent_posts( array $args = array(), string $output = ARRAY_A ): array|false

引数

  • $args:取得条件(numberposts など)
  • $output:返却形式。既定は連想配列

戻り値

投稿データの配列。

使い方(サンプル)

$recent = wp_get_recent_posts( array( 'numberposts' => 3 ) );
foreach ( $recent as $p ) {
	echo esc_html( $p['post_title'] );
}

注意点

  • 既定の戻り値は配列で、オブジェクトではありません。
  • 既定では公開済み・下書き・非公開なども含むため、post_status => 'publish' を指定するのが無難です。

実務での使いどころ

  • 最新の投稿を、配列で取得するとき。
  • サイドバーなどに、新着記事を出すとき。
  • get_posts() の結果を、オブジェクトではなく配列で欲しいとき。

よくあるミスと対処

  • post_status の既定は、下書きや非公開も含む(draft, publish, future, pending, private)。公開済みだけでよいときは、publish を指定する。
  • 戻り値は配列なので、$post->post_title ではなく $post['post_title'] と書く。
  • 取得件数の既定は10件。

NG例

$recent = wp_get_recent_posts( array( 'numberposts' => 5 ) );
foreach ( $recent as $post ) {
	echo $post->post_title; // 配列なので、エラーになる
}

OK例

$recent = wp_get_recent_posts( array(
	'numberposts' => 5,
	'post_status' => 'publish',
) );
foreach ( $recent as $post ) {
	echo esc_html( $post['post_title'] );
}

使い分け早見表

やりたいこと 使うもの
最新の投稿を、配列で取得 wp_get_recent_posts()
最新の投稿を、オブジェクトで取得 get_posts()
ループで表示 WP_Query

関連項目

get_posts()、WP_Query

公式リファレンス:wp_get_recent_posts() | Function | WordPress Developer Resources

コメント

タイトルとURLをコピーしました