概要
get_next_post
関数は、WordPressの投稿内で「1つ後の投稿情報を取得する」ための関数です。この関数は特に以下の機能を実装する際によく使われます。
- 投稿ナビゲーションの実装
- シングルポスト表示時に次の投稿へのリンクを作成
- カスタムテーマの開発
- アーカイブページでの投稿の並び替え
- 関連投稿の表示
- 検索結果に基づく投稿の表示
- 投稿ビジュアルを向上させるUIの構築
- プラグイン内での投稿情報の管理
構文
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 です。
関連する関数
使用可能なバージョン
この関数はWordPress 1.5以降で利用可能です。
コアファイルのパス
wp-includes/post.php
この関数のアクションでの使用可能性
アクション | 使用例 |
---|---|
mu_plugin_loaded | |
registered_post_type | |
plugins_loaded | |
wp_roles_init | |
setup_theme | |
after_setup_theme | |
set_current_user | |
init | |
register_sidebar | |
wp_loaded | |
send_headers | |
parse_query | |
pre_get_posts | 〇 |
wp | |
template_redirect | |
get_header | |
wp_head |
サンプルコード
サンプルコード 1
$next_post = get_next_post();
if (!empty($next_post)) {
echo '<a href="' . get_permalink($next_post->ID) . '">次の投稿: ' . $next_post->post_title . '</a>';
}
このサンプルコードは、次の投稿のリンクを生成し、存在する場合は表示します。投稿が存在しない場合は何も表示されません。
引用元: https://developer.wordpress.org/reference/functions/get_next_post/
サンプルコード 2
$next_post = get_next_post(true);
if ($next_post) {
echo '<div>次の投稿: ' . get_the_title($next_post->ID) . '</div>';
}
このサンプルは、同じターム内の次の投稿を取得し、そのタイトルを表示します。
引用元: https://developer.wordpress.org/reference/functions/get_next_post/
サンプルコード 3
$next_post = get_next_post(false, '', 'category');
if ($next_post) {
echo '<a href="' . get_permalink($next_post->ID) . '">次のカテゴリ投稿: ' . $next_post->post_title . '</a>';
}
このコードは、全てのカテゴリから次の投稿を取得し、そのタイトルとリンクを表示します。
引用元: https://developer.wordpress.org/reference/functions/get_next_post/
サンプルコード 4
$next_post = get_next_post(false, '', 'post_tag');
if ($next_post) {
echo '<h3>次のタグ付き投稿: ' . $next_post->post_title . '</h3>';
}
このサンプルは、タグに基づいて次の投稿を取得し、そのタイトルを見出しとして表示します。
引用元: https://developer.wordpress.org/reference/functions/get_next_post/
サンプルコード 5
$next_post = get_next_post(true, '', 'category');
if ($next_post) {
echo '<span>次の投稿: ' . esc_html($next_post->post_title) . '</span>';
}
このどの投稿が存在する場合、次の投稿のタイトルをエスケープして表示します。これにより、出力の安全性が確保されます。
引用元: https://developer.wordpress.org/reference/functions/get_next_post/