ワードプレスのget_next_posts_link関数の使用方法・解説

概要

get_next_posts_link関数は、WordPressの投稿やアーカイブページで、次のページへのリンクを簡単に取得するために用いられます。この関数は、ページネーション機能を実装する際によく使われ、特に以下のような機能が必要な場合に役立ちます。

  1. 投稿リストのナビゲーション
  2. タクソノミーアーカイブのページネーション
  3. カスタムクエリのページネーション
  4. カテゴリページでの投稿移動
  5. タグページの表示
  6. 検索結果のナビゲーション
  7. 日付アーカイブのリンク作成
  8. フロントエンドのユーザー体験の向上

構文

get_next_posts_link( $label, $max_page );

パラメータ

  • $label (string, 必須): 次のページへのリンクテキスト。例: “次へ”
  • $max_page (int, 任意): ページ数の上限。指定しない場合は全体のページ数を自動で計算します。

戻り値

取得した次ページへのリンク。指定された条件に合わない場合は null を返します。

関連する関数

使用可能なバージョン

この関数は WordPress 2.5.0 以降で使用可能です。

コアファイルのパス

wp-includes/query.php

サンプルコード

1. 基本的な使用例

このコードは、次のページへのリンクテキストを “次の投稿” として出力します。

if ( get_next_posts_link() ) {
    echo get_next_posts_link( '次の投稿' );
}

引用元: https://developer.wordpress.org/reference/functions/get_next_posts_link/

2. 最大ページ数を指定する例

このコードは、最大ページ数を明示的に指定したうえで次ページへのリンクを出力します。

$max_pages = 5;
echo get_next_posts_link( '次へ', $max_pages );

引用元: https://developer.wordpress.org/reference/functions/get_next_posts_link/

3. アーカイブページでの使用例

アーカイブページで次の投稿のリンクを表示する方法です。

if ( have_posts() ) {
    while ( have_posts() ) {
        the_post();
        // 投稿内容表示
    }
    echo get_next_posts_link( '次のページ' );
}

引用元: https://developer.wordpress.org/reference/functions/get_next_posts_link/

4. タクソノミーアーカイブでの使用例

タクソノミーアーカイブに次ページのリンクを追加する方法です。

if ( is_tax() ) {
    echo get_next_posts_link( '次のアイテム' );
}

引用元: https://developer.wordpress.org/reference/functions/get_next_posts_link/

5. カスタムクエリの使用例

カスタムクエリを使用して投稿を取得し、次ページへのリンクを表示します。

$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$query = new WP_Query( array( 'post_type' => 'post', 'paged' => $paged ) );

if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
        // 投稿内容表示
    }
    echo get_next_posts_link( '次の投稿', $query->max_num_pages );
}
wp_reset_postdata();

引用元: https://developer.wordpress.org/reference/functions/get_next_posts_link/

この関数のアクションでの使用可能性

アクション 使用例
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

非推奨または削除されたバージョン

特定のWordPressバージョンでこの関数が非推奨または削除された情報はありません。

この関数について質問する


上の計算式の答えを入力してください