wp_get_recent_posts()


WordPress関数wp_get_recent_posts()は、サイト上の最近の投稿を取得するために使用されます。

シンタックス

wp_get_recent_posts( array $args = array(), string $output = OBJECT );

引数の説明:

  • $args (array) — 投稿の取得条件を設定する引数の配列。
  • $output (string) — 出力フォーマット。デフォルトはOBJECT

主な引数の内容:

  • numberposts (int) — 取得する投稿の数。デフォルトは5。
  • post_status (string) — 投稿の状態。例: 'publish', 'draft'
  • post_type (string) — 投稿タイプ。デフォルトは'post'
  • orderby (string) — 並べ替えの基準。例: 'date', 'title'
  • order (string) — 並び順。'ASC' または 'DESC'

例 1: 最近の投稿を取得して表示

最近の投稿を取得し、タイトルを表示します。

<?php
$recent_posts = wp_get_recent_posts( array( 'numberposts' => 3 ) );
foreach( $recent_posts as $post ){
    echo '<h4>' . $post['post_title'] . '</h4>';
}
?>

例 2: 特定の状態の投稿を取得

公開済みの投稿のみ取得します。

<?php
$recent_posts = wp_get_recent_posts( array( 'post_status' => 'publish', 'numberposts' => 5 ) );
foreach( $recent_posts as $post ){
    echo '<p>' . $post['post_title'] . '</p>';
}
?>

例 3: カスタム投稿タイプの取得

カスタム投稿タイプ'event'の投稿を取得します。

<?php
$recent_posts = wp_get_recent_posts( array( 'post_type' => 'event', 'numberposts' => 3 ) );
foreach( $recent_posts as $post ){
    echo '<li>' . $post['post_title'] . '</li>';
}
?>

例 4: 並べ替え順を指定

日付の降順で投稿を取得します。

<?php
$recent_posts = wp_get_recent_posts( array( 'orderby' => 'date', 'order' => 'DESC' ) );
foreach( $recent_posts as $post ){
    echo '<div>' . $post['post_title'] . '</div>';
}
?>

例 5: 投稿リンク付きで表示

最近の投稿タイトルにリンクを追加して表示します。

<?php
$recent_posts = wp_get_recent_posts( array( 'numberposts' => 5 ) );
foreach( $recent_posts as $post ){
    echo '<a href="' . get_permalink( $post['ID'] ) . '">' . $post['post_title'] . '</a><br>';
}
?>

注意事項

  • wp_get_recent_posts()はデフォルトで最新5件の投稿を返します。
  • カスタムクエリや条件が多い場合は、WP_Queryを検討してください。

関連機能: