get_next_post()


WordPressのget_next_post()関数は、現在の投稿の次に位置する投稿を取得するために使用されます。

シンタックス

get_next_post( $in_same_term = false, $excluded_terms = '', $taxonomy = 'category' );

引数の説明

  • $in_same_term (bool) — 同じタクソノミー内で次の投稿を取得するかどうか。デフォルトはfalse
  • $excluded_terms (string|array) — 除外するタクソノミーのIDまたはスラッグ。
  • $taxonomy (string) — 使用するタクソノミーの名前。デフォルトは'category'

戻り値

  • WP_Post|null — 次の投稿のオブジェクト、または見つからない場合はnull

例1: 次の投稿を取得して表示する

次の投稿が存在する場合、そのタイトルを表示します。

<?php
$next_post = get_next_post();
if ( $next_post ) {
    echo '<a href="' . get_permalink( $next_post->ID ) . '">' . esc_html( $next_post->post_title ) . '</a>';
}
?>

例2: 同じカテゴリ内で次の投稿を取得

現在の投稿と同じカテゴリに属する次の投稿を取得します。

<?php
$next_post = get_next_post( true );
if ( $next_post ) {
    echo '<a href="' . get_permalink( $next_post->ID ) . '">' . esc_html( $next_post->post_title ) . '</a>';
}
?>

例3: 特定のカテゴリを除外して次の投稿を取得

カテゴリID3を除外して次の投稿を取得します。

<?php
$next_post = get_next_post( false, '3' );
if ( $next_post ) {
    echo '<a href="' . get_permalink( $next_post->ID ) . '">' . esc_html( $next_post->post_title ) . '</a>';
}
?>

例4: カスタムタクソノミー内で次の投稿を取得

'genre'というカスタムタクソノミー内で次の投稿を取得します。

<?php
$next_post = get_next_post( true, '', 'genre' );
if ( $next_post ) {
    echo '<a href="' . get_permalink( $next_post->ID ) . '">' . esc_html( $next_post->post_title ) . '</a>';
}
?>

例5: 次の投稿が存在しない場合の処理

次の投稿が存在しない場合の代替テキストを表示します。

<?php
$next_post = get_next_post();
if ( $next_post ) {
    echo '<a href="' . get_permalink( $next_post->ID ) . '">' . esc_html( $next_post->post_title ) . '</a>';
} else {
    echo '次の投稿はありません。';
}
?>

注意事項

  • get_next_post()関数は、標準の投稿タイプに対して動作します。他の投稿タイプで使用する場合は、カスタムクエリが必要になることがあります。
  • キャッシュが効くため、取得したデータは変更しないよう注意してください。

関連機能: