WordPress Logo WordPress ページネーション ページャー

前後の投稿や一覧ページ、分割されたページへのリンクを出力するページャーやページネーションの使い方や設定方法についての覚え書きです。

基本的な関数の使い方から前後の投稿へのリンクを表示する際にアイキャッチ画像を表示したり、ページネーションでの出力を Bootstrap の形式に変換する方法、the_post_navigation() などで自動的に出力されるナビゲーションマークアップのカスタマイズ方法なども掲載しています。

更新日:2023年02月21日

作成日:2019年06月24日

投稿の個別ページで前後の投稿へリンクする関数

投稿の個別ページで前後の投稿へのリンクを表示するには以下のような方法があります。

  • previous_post_link() と next_post_link() を使う方法
  • the_post_navigation() を使う方法(バージョン 4.1.0 から導入)

通常は個別ページ(single.php など)のループ内で使用します。

<?php if(have_posts()) : ?>
<?php while(have_posts()) : the_post(); ?>
・・・中略・・・
<?php the_content(); ?>
・・・中略・・・
<?php
//リンクを出力:the_post_navigation() を使う場合の例
the_post_navigation( array(
  'prev_text' => '前へ: %title',
  'next_text' => '%title: 次へ',
) );
?>
<?php endwhile; ?>
<?php endif; ?>

previous_post_link() と next_post_link() を使う方法

previous_post_link()next_post_link() を使って前後の投稿へのリンクを個々に出力します。

以下は nav 要素と ul li 要素でマークアップする例です。

&laquo; は「«」、&raquo; は「»」の文字参照です。

<nav class="navigation post-navigation" role="navigation">
  <ul class="nav-links">
    <li class="nav-previous"><?php previous_post_link('%link', '&laquo; %title'); ?></li>
    <li class="nav-next"><?php next_post_link('%link', '%title &raquo;'); ?></li>
  </ul>
</nav>

以下は nav 要素と div 要素でマークアップする例です。

<nav class="navigation post-navigation" role="navigation">
  <div class="nav-links">
    <div class="nav-previous"><?php previous_post_link('%link', '&laquo; %title'); ?></div>
    <div class="nav-next"><?php next_post_link('%link', '%title &raquo;'); ?></div>
  </div>
</nav>

先頭のページでは next_post_link() による次の(より新しい)投稿へのリンクは出力されず、最後のページでは previous_post_link() による前の(より古い)投稿へのリンクは出力されません。

そのため、空の div 要素が出力されないようにするには get_previous_post_link() get_next_post_link() を使って以下のように記述することができます。

<nav class="navigation post-navigation" role="navigation">
  <div class="nav-links">
  <?php if( get_previous_post_link() ) : ?>
    <div class="nav-previous"><?php previous_post_link('%link', '&laquo; %title'); ?></div>
  <?php endif; ?>
  <?php if( get_next_post_link() ) : ?>
    <div class="nav-next"><?php next_post_link('%link', '%title &raquo;'); ?></div>
  <?php endif; ?>
  </div>
</nav>

previous_post_link() と next_post_link() を使う場合、上記のように div 要素などを使って自前で HTML をマークアップする必要がありますが、バージョン 4.1.0 から導入された the_post_navigation() ではその必要がありません。

the_post_navigation() を使う方法

バージョン 4.1.0 から導入された the_post_navigation() を使うと、前後の投稿へのリンクをまとめて出力できます。

少ないマークアップで記述できるのと、パラメータの指定も連想配列形式なので簡潔に記述できます。

以下は、前の投稿のリンクに「« 前の投稿のタイトル」、次の投稿のリンクに「次の投稿のタイトル »」と表示する例です。%title にはそれぞれの投稿のタイトルが入ります。

<?php
the_post_navigation( array(
  'prev_text' => '&laquo; %title',
  'next_text' => '%title &raquo;',
) );
?>

以下のような HTML が出力されます。

<nav class="navigation post-navigation" role="navigation">
  <h2 class="screen-reader-text">投稿ナビゲーション</h2>
  <div class="nav-links">
    <div class="nav-previous">
      <a href="http://localhost/news/sample-1/" rel="prev">« サンプル1</a>
    </div>
    <div class="nav-next">
      <a href="http://localhost/news/sample-3/" rel="next">サンプル3 »</a>
    </div>
  </div>
</nav>

以下はリンクを左右にフロートさせるスタイルの指定例です。

/* スクリーンリーダー限定テキスト: the_post_navigation() 用 */
.screen-reader-text {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  white-space: nowrap;
  border: 0;
}
/* 前の投稿へのリンクを左寄せ */
.nav-previous {
  float: left;
}
/* 次の投稿へのリンクを右寄せ */
.nav-next {
  float: right;
}
/* リンクが長い場合に重ならないように */
.nav-previous, .nav-next {
  max-width: 45%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

それぞれの関数の詳細は以下をご覧ください。

the_post_navigation

個別ページで前後の投稿へのリンクを表示します。バージョン 4.1.0 から導入。

the_post_navigation( $args )

パラメータ
$args(配列):(オプション)以下を連想配列で指定します。初期値:array()
キー 意味(型) 初期値
'prev_text' 前の投稿へのリンク文字列。(文字列) '%title'(投稿のタイトル)
'next_text' 次の投稿へのリンク文字列。(文字列) '%title'(投稿のタイトル)
'in_same_term' 現在の投稿と同じカテゴリー(ターム)の投稿に限定するかどうかを指定。カスタムタクソノミーを使用していて true を指定する場合は、$taxonomy で適切なタクソノミーを指定。(真偽値) false(限定しない)
'excluded_terms' 表示させたくない投稿のカテゴリー ID(ターム ID)を指定。複数のカテゴリー(ターム)を除外する場合は配列またはコンマで区切りで指定。(文字列/配列) ''
'taxonomy' $in_same_term を true にした場合に指定するタームのタクソノミー。(文字列) 'category'
'screen_reader_text' 読み上げ(スクリーンリーダー)用のテキスト。h2 要素で表示されます。(文字列) '投稿ナビゲーション'
戻り値
なし
利用可能箇所
個別ページ(single.php など)のテンプレート

prev_text/next_text

前後の記事のタイトルにそれぞれ「前へ:」と「:次へ」と言う文字を追加したリンクを表示するには、以下のように記述することができます。

%title にはそれぞれ前後の投稿のタイトルが入ります。

<?php
the_post_navigation( array(
  'prev_text' => '前へ: %title',
  'next_text' => '%title: 次へ',
) );
?>

個別ページのテンプレートに上記を記述すると、例えば以下のような HTML が出力されます。

<nav class="navigation post-navigation" role="navigation">
  <h2 class="screen-reader-text">投稿ナビゲーション</h2>
  <div class="nav-links">
    <div class="nav-previous">
      <a href="http://localhost/news/sample-1/" rel="prev">前へ:サンプル1</a>
    </div>
    <div class="nav-next">
      <a href="http://localhost/news/sample-3/" rel="next">サンプル3:次へ</a>
    </div>
  </div>
</nav>

HTML も使用できるので画像やアイコンフォントを表示することもできます。以下はアイコンフォントを表示する例です。

<?php
the_post_navigation( array(
  'prev_text' => '<i class="fas fa-angle-left"></i> 前へ: %title',
  'next_text' => '%title: 次へ <i class="fas fa-angle-right"></i>',
) );
?>

in_same_term

引数 $in_same_term に「true」を指定すると、現在の投稿と同じカテゴリー(ターム)に属する前の投稿へのリンクを出力します。

previous_post_link() や next_post_link() とは異なり連想配列で指定しているため、$in_same_term を指定する場合でも、prev_text や next_text を省略することができます。

<?php
the_post_navigation( array(
  'in_same_term' => true, //同一カテゴリー限定
) );
?>

※カスタム投稿タイプの個別ページで $in_same_term に「true」を指定して同一タームに限定する場合は、引数 $taxonomy に register_taxonomy() で登録したカスタムタクソノミー名を指定する必要があります。

以下は rental_cat と言うカスタムタクソノミーの同一のタームに限定する例です。

ID を直接指定する他に、get_cat_ID()get_category_by_slug() を使って指定することもできます。

<?php
the_post_navigation( array(
  'in_same_term' => true, //同一ターム限定
  'taxonomy' => 'rental_cat' //タクソノミー指定
) );
?>

excluded_terms

$excluded_terms で、カテゴリー ID(ターム ID )を指定すると、そのカテゴリー(ターム)の投稿を除外することができます。

以下は特定の1つのカテゴリーを除外する例です。

<?php
the_post_navigation( array(
  //カテゴリー ID が 3 のカテゴリーを除外
  'excluded_terms' => 3,
) );
?>

<?php
the_post_navigation( array(
  //カテゴリー名が「コラム」のカテゴリーを除外
  'excluded_terms' => get_cat_ID('コラム'),
) );
?>

<?php
the_post_navigation( array(
  //カテゴリーのスラッグが「column」のカテゴリーを除外
  //スラッグからオブジェクトを取得してそのプロパティ term_id から ID を取得)
  'excluded_terms' => get_category_by_slug('column')->term_id,
) );
?>

カスタムタクソノミーの場合は、get_term_by() を使って指定することができます。

<?php
the_post_navigation( array(
  //ターム名が「大型」のタームを除外
  'excluded_terms' => get_term_by('name', '大型', 'rental_cat')->term_id,
  //以下はタームのスラッグが「large」のタームを除外する場合
  //'excluded_terms' => get_term_by('slug', 'large', 'rental_cat')->term_id,
) );
?>

以下は複数のカテゴリーを除外する例です。

<?php
the_post_navigation( array(
  //カテゴリー ID が 3, 35, 36 のカテゴリーを除外(配列)
  'excluded_terms' => array(3, 35, 36),
  //以下はカンマ区切りで指定する場合
  //'excluded_terms' => '3, 35, 36',
) );
?>

screen_reader_text

読み上げ(スクリーンリーダー)用のテキストは、デフォルトでは「投稿ナビゲーション(英語の場合は Post navigation)」と h2 要素でマークアップされて表示されます。

以下は表示される(読み上げられる)テキストを「前後の投稿へのリンク」に変更する例です。

<?php
the_post_navigation( array(
  'screen_reader_text' => '前後の投稿へのリンク'
) );
?> 

表示されるテキスト(h2 要素)には screen-reader-text クラスが付与されるので、スクリーンリーダー限定テキストとしてスクリーンリーダには読み上げられるが画面には表示しないようにするには以下のようなスタイルを指定します。

.screen-reader-text {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  white-space: nowrap;
  border: 0;
}

スタイル

以下は Font Awesome のアイコンフォントをリンク文字列(%title)の前後に挿入する例です。

<?php
the_post_navigation( array(
  'prev_text' => '<i class="fas fa-angle-left"></i> %title',
  'next_text' => '%title <i class="fas fa-angle-right"></i></i>',
) );
?>

以下のような HTML が出力されます。

<nav class="navigation post-navigation" role="navigation">
  <h2 class="screen-reader-text">投稿ナビゲーション</h2>
  <div class="nav-links">
    <div class="nav-previous">
      <a href="http://localhost/news/sample-1/" rel="prev"><i class="fas fa-angle-left"></i> サンプル1</a>
    </div>
    <div class="nav-next">
      <a href="http://localhost/news/sample-3/" rel="next">サンプル3 <i class="fas fa-angle-right"></i></a>
    </div>
  </div>
</nav>

スタイルを指定するには、出力される要素やそのクラスを使います。上記の場合は、必要に応じてアイコン(i 要素)にもスタイルを適用できます。

以下はリンクを左右にフロートさせる例です。

/* スクリーンリーダー限定テキスト */
.screen-reader-text {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  white-space: nowrap;
  border: 0;
}
/* フロート */
.nav-previous {
  float: left;
}
.nav-next {
  float: right;
}
/* リンクが長い場合に重ならないように */
.nav-previous, .nav-next {
  max-width: 45%;
  white-space: pre-wrap;
}

上記の例ではリンクの文字列を折り返すようにしていますが、折り返さずに非表示にするには以下のように指定します。

white-space: nowrap で自動改行を禁止して、overflow: hidden で幅が 45% 以上の部分は非表示にし、text-overflow: ellipsis で非表示部分があれば省略記号を表示します。

.nav-previous, .nav-next {
  max-width: 45%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

以下は the_post_navigation() のソースです。

function the_post_navigation( $args = array() ) {
  echo get_the_post_navigation( $args );
}

get_the_post_navigation() の実行結果を出力しています。

get_the_post_navigation() のソースは以下のようになっています。

前後の投稿へのリンクは get_previous_post_link() get_next_post_link() を使って生成して、nav 要素のマークアップはシステム関数の _navigation_markup() を使っています。

function get_the_post_navigation( $args = array() ) {
  $args = wp_parse_args(
    $args,
    array(
      'prev_text'          => '%title',
      'next_text'          => '%title',
      'in_same_term'       => false,
      'excluded_terms'     => '',
      'taxonomy'           => 'category',
      'screen_reader_text' => __( 'Post navigation' ),
    )
  );

  $navigation = '';

  $previous = get_previous_post_link(
    '<div class="nav-previous">%link</div>',
    $args['prev_text'],
    $args['in_same_term'],
    $args['excluded_terms'],
    $args['taxonomy']
  );

  $next = get_next_post_link(
    '<div class="nav-next">%link</div>',
    $args['next_text'],
    $args['in_same_term'],
    $args['excluded_terms'],
    $args['taxonomy']
  );

  // Only add markup if there's somewhere to navigate to.
  if ( $previous || $next ) {
    $navigation = _navigation_markup( $previous . $next, 'post-navigation', $args['screen_reader_text'] );
  }

  return $navigation;
}

上記ソースの16行目と24行目で get_previous_post_link() と get_next_post_link() を使っています。

その際、パラメータ $format にそれぞれ '<div class="nav-previous">%link</div>' と '<div class="nav-next">%link</div>', が、$link には $args['prev_text'] や $args['next_text'], が渡されています。

以下は get_previous_post_link() と get_next_post_link() のソースです。

function get_previous_post_link( $format = '&laquo; %link', $link = '%title', $in_same_term = false, $excluded_terms = '', $taxonomy = 'category' ) {
  return get_adjacent_post_link( $format, $link, $in_same_term, $excluded_terms, true, $taxonomy );
}

function get_next_post_link( $format = '%link &raquo;', $link = '%title', $in_same_term = false, $excluded_terms = '', $taxonomy = 'category' ) {
  return get_adjacent_post_link( $format, $link, $in_same_term, $excluded_terms, false, $taxonomy );
} 

それぞれのソースを確認すると、共に get_adjacent_post_link() と言う関数の実行結果を返しています。

get_adjacent_post_link() のソースは以下のようになっていて、get_adjacent_post() で隣接する投稿を取得してそのタイトルを取得したり、パーマリンクを取得してリンクの href 属性に設定しています。

値を返す前に、previous_post_link または next_post_link と言うフィルタを適用しています。

function get_adjacent_post_link( $format, $link, $in_same_term = false, $excluded_terms = '', $previous = true, $taxonomy = 'category' ) {
  if ( $previous && is_attachment() ) {
    $post = get_post( get_post()->post_parent );
  } else {
    $post = get_adjacent_post( $in_same_term, $excluded_terms, $previous, $taxonomy );
  }

  if ( ! $post ) {
    $output = '';
  } else {
    $title = $post->post_title;

    if ( empty( $post->post_title ) ) {
      $title = $previous ? __( 'Previous Post' ) : __( 'Next Post' );
    }

    /** This filter is documented in wp-includes/post-template.php */
    $title = apply_filters( 'the_title', $title, $post->ID );

    $date = mysql2date( get_option( 'date_format' ), $post->post_date );
    $rel  = $previous ? 'prev' : 'next';

    $string = '<a href="' . get_permalink( $post ) . '" rel="' . $rel . '">';
    $inlink = str_replace( '%title', $title, $link );
    $inlink = str_replace( '%date', $date, $inlink );
    $inlink = $string . $inlink . '</a>';

    $output = str_replace( '%link', $inlink, $format );
  }

  $adjacent = $previous ? 'previous' : 'next';

  /**
   * Filters the adjacent post link.
   * The dynamic portion of the hook name, `$adjacent`, refers to the type
   * of adjacency, 'next' or 'previous'.
   * @since 2.6.0
   * @since 4.2.0 Added the `$adjacent` parameter.
   * @param string  $output   The adjacent post link.
   * @param string  $format   Link anchor format.
   * @param string  $link     Link permalink format.
   * @param WP_Post $post     The adjacent post.
   * @param string  $adjacent Whether the post is previous or next.
   */
  return apply_filters( "{$adjacent}_post_link", $output, $format, $link, $post, $adjacent );
}
リンク(a 要素)にクラスを追加

the_post_navigation() で出力されるリンク(a 要素)に JavaScript を使ってクラスを追加する方法です。

例えば、以下を記述した場合、

<?php
the_post_navigation( array(
  'prev_text' => '&larr; Previous ',
  'next_text' => 'Next &rarr;',
) );
?>

以下のような HTML が出力されます。リンクのスタイルをカスタマイズする場合、.nav-previous a などのセレクタを使うこともできますが、既存のスタイルを適用したい場合、JavaScript を使って a 要素にクラスを追加することもできます。

<nav class="navigation post-navigation" role="navigation" aria-label="投稿">
  <h2 class="screen-reader-text">投稿ナビゲーション</h2>
  <div class="nav-links">
    <div class="nav-previous">
      <a href="http://localhost/xxxx" rel="prev">← Previous </a>
    </div>
    <div class="nav-next">
      <a href="http://localhost/xxxx/" rel="next">Next →</a>
    </div>
  </div>
</nav>

以下は上記のリンク(a 要素)に JavaScript を使って Bootstrap のクラス(.btn と .btn-outline-success)を追加する例です。

JavaScript
//.nav-previous の子要素の a 要素を取得
const navPrevA = document.querySelector('.nav-previous a');
//上記で取得した要素が存在すれば
if(navPrevA) {
  //要素の classList プロパティ
  let navPrevAClass = navPrevA.classList;
  //.btn と .btn-outline-success を追加
  navPrevAClass.add('btn');
  navPrevAClass.add('btn-outline-success');
}

const navNextA = document.querySelector('.nav-next a');
if(navNextA) {
  let navNextAClass = navNextA.classList;
  navNextAClass.add('btn');
  navNextAClass.add('btn-outline-success');
}

以下のようにリンクにクラスが追加されます。

<nav class="navigation post-navigation" role="navigation" aria-label="投稿">
  <h2 class="screen-reader-text">投稿ナビゲーション</h2>
  <div class="nav-links">
    <div class="nav-previous">
      <!-- クラスを追加 -->
      <a href="http://localhost/xxxx/" rel="prev" class="btn btn-outline-success">← Previous </a>
    </div>
    <div class="nav-next">
      <!-- クラスを追加 -->
      <a href="http://localhost/xxxx/" rel="next" class="btn btn-outline-success">Next →</a>
    </div>
  </div>
</nav>

関連ページ:WordPress CSS や JavaScript ファイルの読み込み

アイキャッチ画像を表示

the_post_navigation() で出力されるリンクにアイキャッチ画像を表示する方法です。

the_post_navigation() の内部で使用されている get_adjacent_post_link() の戻り値は next_post_link 及び previous_post_link フィルタが適用されるので、それらのフィルタを利用します。

アイキャッチ画像は get_the_post_thumbnail() で取得することができ、第2パラメータでサイズを指定することができます。

アイキャッチ画像がない場合は、テーマの images フォルダにデフォルトの画像を用意しておき、それを表示します。

function add_thumbnail_to_post_navigation( $output, $format, $link, $post, $adjacent ){

  if( has_post_thumbnail( $post ) ){
    //第2パラメータでサイズを指定可能 thumbnail, medium など
    $thumbnail_image = get_the_post_thumbnail( $post, 'thumbnail' );
  }else{
    //画像がない場合はデフォルトの画像を表示
    $thumbnail_image = '<img src="' . get_theme_file_uri( 'images/no-image.png' ) . '" alt="">';
  }
  //出力される HTML に上記で取得した画像要素を追加
  $output = str_replace( '<div class="nav-' . $adjacent . '">', '<div class="nav-' . $adjacent . '">' . $thumbnail_image, $output );

  return $output;
}
add_filter( 'next_post_link', 'add_thumbnail_to_post_navigation', 10, 5 );
add_filter( 'previous_post_link', 'add_thumbnail_to_post_navigation', 10, 5 );

the_post_navigation() の場合、引数で受け取る $output には get_the_post_navigation() で生成された '<div class="nav-previous">%link</div>' などの HTML が含まれています。

11行目では、str_replace() を使って <div class="nav-previous"> を <div class="nav-previous"><img src="path/to/theme/images/xxx.png" alt=""> などに変換して画像要素を追加しています。

投稿の一覧ページで前後の一覧ページへリンクする関数

一覧(アーカイブ)ページでは、表示設定で設定した「1ページに表示する最大投稿数」以上の投稿がある場合は、ページが分割されます。

分割後の前後のページに移動するリンクを出力するには以下のような方法があります。

  • previous_posts_link() と next_posts_link() を使う方法
  • the_posts_navigation() を使う方法(バージョン 4.1.0 から導入)
  • ページネーションを出力(次項)

アーカイブページなどのテンプレートで使用します。

<?php if(have_posts()) : ?>
<?php while(have_posts()) : the_post(); ?>
・・・中略・・・
<?php endwhile; ?>
<?php the_posts_navigation(); //リンクを出力 ?>
<?php else : ?>
・・・中略・・・
<?php endif; ?>

※個別ページで前後の投稿へのリンクを表示する際に使用する以下の関数と名前が似ているので紛らわしいです(posts と post の違い)。

previous_posts_link() と next_posts_link() を使う方法

previous_posts_link() と next_posts_link() を使って前後の一覧ページへのリンクを個々に出力します。

  • previous_posts_link() :分割後の前の(より最近の)一覧ページへのリンクを出力
  • next_posts_link() :分割後の次の(より過去の)一覧ページへのリンクを出力

(参考:個別ページで使う関数と previous と next の方向が違います。)

以下はパラメータなし(デフォルト)で使用する例です。

previous_posts_link() と next_posts_link() はリンク(a 要素)を出力するだけなので div 要素や ul li 要素などでマークアップします。

以下は div 要素でマークアップする例です。

<nav class="navigation posts-navigation" role="navigation">
  <div class="nav-links">
    <div class="nav-previous"><?php previous_posts_link(); ?></div>
    <div class="nav-next"><?php next_posts_link(); ?></div>
  </div>
</nav>

一覧ページが3つのページに分割されている場合、先頭のページでは以下のような出力になります。

先頭のページでは previous_posts_link() による出力はありません。

<nav class="navigation posts-navigation" role="navigation">
  <div class="nav-links">
    <div class="nav-previous"></div><!-- 出力なし -->
    <div class="nav-next"><a href="http://localhost/page/2/">次ページへ »</a></div>
  </div>
</nav>

一覧ページが3つのページに分割されている場合、2番目のページでは以下のような出力になります。

<nav class="navigation posts-navigation" role="navigation">
  <div class="nav-links">
    <div class="nav-previous"><a href="http://localhost/">« 前ページへ</a></div>
    <div class="nav-next"><a href="http://localhost/page/3/">次ページへ »</a></div>
  </div>
</nav>

一覧ページが3つのページに分割されている場合、最後のページでは以下のような出力になります。

最後のページでは next_posts_link() による出力はありません。

<nav class="navigation posts-navigation" role="navigation">
  <div class="nav-links">
    <div class="nav-previous"><a href="http://localhost/page/2/">« 前ページへ</a></div>
    <div class="nav-next"></div><!-- 出力なし -->
  </div>
</nav>

先頭や最後のページで空の div 要素を出力しない

上記の例のように先頭や最後のページでは空の div 要素が残ってしまいます。

空の div 要素を出力しないようにするには get_previous_posts_link()get_next_posts_link() を使って以下のように記述します。

<nav class="navigation posts-navigation" role="navigation">
  <div class="nav-links">
  <?php if( get_previous_posts_link() ) : ?>
    <div class="nav-previous"><?php previous_posts_link(); ?></div>
  <?php endif; ?>
  <?php if( get_next_posts_link() ) : ?>
    <div class="nav-next"><?php next_posts_link(); ?></div>
  <?php endif; ?>
  </div>
</nav>

以下は、1ページに表示する件数を取得して、例えば「« 前の10件へ」や「次の10件へ »」のように表示する例です。

<nav class="navigation posts-navigation" role="navigation">
  <div class="nav-links">
  <?php if( get_previous_posts_link() ) : ?>
    <div class="nav-previous"><?php previous_posts_link('&laquo; 前の'. get_query_var( 'posts_per_page') . '件へ'); ?></div>
  <?php endif; ?>
  <?php
    if( get_next_posts_link() ) : ?>
    <div class="nav-next"><?php next_posts_link('次の'. get_query_var( 'posts_per_page') . '件へ &raquo;'); ?></div>
  <?php endif; ?>
  </div>
</nav>

the_posts_navigation() を使う方法

バージョン 4.1.0 から導入された the_posts_navigation() を使うと、少ない記述で前後の一覧ページへのリンクをまとめて出力できます。

パラメータなしで以下のように記述するだけで

<?php the_posts_navigation(); ?>

以下のような HTML が出力されます。

出力される HTML は nav 要素のクラス posts-navigation 以外は the_post_navigation() と同じです。

<nav class="navigation posts-navigation" role="navigation">
  <h2 class="screen-reader-text">投稿ナビゲーション</h2>
  <div class="nav-links">
    <div class="nav-previous"><a href="http://localhost/page/3/">過去の投稿</a>
    </div>
    <div class="nav-next"><a href="http://localhost/">新しい投稿</a>
    </div>
  </div>
</nav>

パラメータを指定すれば、リンクやスクリーンリーダー用の文字を変更することができます。

the_posts_navigation() の出力をカスタマイズするには、get_the_posts_navigation() で HTML を取得して必要に応じて変換などします。

それぞれの関数の詳細は以下をご覧ください。

the_posts_navigation

一覧ページが分割されている場合に、表示中の一覧ページで前後の一覧ページへのリンクを表示します。バージョン 4.1.0 から導入。

the_posts_navigation( $args )

パラメータ
$args(配列):(オプション)以下を連想配列で指定します。初期値:array()
キー 意味(型) 初期値
'prev_text' 前の一覧ページへのリンク文字列。(文字列) 'Older posts'(過去の投稿)
'next_text' 次の一覧ページへのリンク文字列。(文字列) 'Newer posts'(新しい投稿)
'screen_reader_text' 読み上げ(スクリーンリーダー)用のテキスト。h2 要素で表示されます。(文字列) 'Posts navigation'(投稿ナビゲーション)
戻り値
なし
利用可能箇所
アーカイブ(一覧)ページのテンプレートやサブループを使っているページなど

関連項目:nav 要素のカスタマイズ

アーカイブページなどの複数の投稿を出力するテンプレートで使用します。

<?php if(have_posts()) : ?>
<?php while(have_posts()) : the_post(); ?>
・・・中略・・・
<?php endwhile; ?>
<?php the_posts_navigation(); //リンクを出力 ?>
<?php else : ?>
・・・中略・・・
<?php endif; ?>

prev_text/next_text

prev_text と next_text を指定すればリンクのテキストを変更することができます。

HTML も記述できるので画像やアイコンフォントも表示できます。

<?php
the_posts_navigation(array(
  'prev_text' => '<i class="fas fa-angle-left"></i> 前へ',
  'next_text' => '次へ <i class="fas fa-angle-right"></i>',
));
?>

以下のように記述すれば1ページに表示する件数を取得して、例えば「前の10件へ」「次の10件へ」のように表示されます。

<?php
the_posts_navigation(array(
  'prev_text' => '前の'. get_query_var( 'posts_per_page') . '件へ',
  'next_text' => '次の'. get_query_var( 'posts_per_page') . '件へ ',
));
?>

screen_reader_text

読み上げ(スクリーンリーダー)用のテキストは、デフォルトでは「投稿ナビゲーション(英語の場合は Posts navigation)」と h2 要素でマークアップされて表示されます。

以下は表示される(読み上げられる)テキストを「前後の一覧ページへのリンク」に変更する例です。

<?php
the_posts_navigation( array(
  'screen_reader_text' => '前後の一覧ページへのリンク'
) );
?> 

スクリーンリーダー限定テキストとして、スクリーンリーダには読み上げられるが画面には表示しないようにするには「screen_reader_text(the_post_navigation)」を参照ください。

出力される HTML は nav 要素のクラス posts-navigation 以外は the_post_navigation() と同じなので、必要に応じてこのクラスを利用して the_post_navigation() と異なるスタイルを適用することができます。

the_post_navigation() の場合、nav 要素には post-navigation と言うクラス(s が付かない)が付与されます。

スタイルの指定例は the_post_navigation() のスタイルの項をご覧ください。

以下は the_posts_navigation() のソースです。

get_the_posts_navigation() の実行結果を出力しています。

function the_posts_navigation( $args = array() ) {
  echo get_the_posts_navigation( $args );
}

以下は get_the_posts_navigation() のソースです。

function get_the_posts_navigation( $args = array() ) {
  $navigation = '';

  // Don't print empty markup if there's only one page.
  if ( $GLOBALS['wp_query']->max_num_pages > 1 ) {
    $args = wp_parse_args(
      $args,
        array(
          'prev_text'          => __( 'Older posts' ),
          'next_text'          => __( 'Newer posts' ),
          'screen_reader_text' => __( 'Posts navigation' ),
        )
    );

    $next_link = get_previous_posts_link( $args['next_text'] );
    $prev_link = get_next_posts_link( $args['prev_text'] );

    if ( $prev_link ) {
      $navigation .= '<div class="nav-previous">' . $prev_link . '</div>';
    }

    if ( $next_link ) {
      $navigation .= '<div class="nav-next">' . $next_link . '</div>';
    }

    $navigation = _navigation_markup( $navigation, 'posts-navigation', $args['screen_reader_text'] );
  }

  return $navigation;
}