the_posts_navigation()の基本的な使い方

アーカイブ系ページのページネーション(前後ページ)を実装(the_posts_navigation)

WP4.1以降で使えます。
以前は、previous_posts_link(), next_posts_link()を利用していました。

仕様

<?php the_posts_navigation( $args ) ?>
パラメータ初期値説明
prev_textOlder posts
(JP:過去の投稿)
現在の次のセットへのリンクテキスト
next_textNewer posts
(JP:新しい投稿)
現在の前のセットへのリンクテキスト
screen_reader_textPosts navigation
(JP:投稿ナビゲーション)
スクリーンリーダー用テキスト

※今の所ページネーション系でこの関数だけ、next_text側が新しいページになる点に注意
※表示は利用言語によって異なる。日本語は(JP:)

初期値

<?php
	the_post_navigation( array(
		'prev_text'          => __( 'Older posts', 'textdomain' ),
		'next_text'          => __( 'Newer posts', 'textdomain' ),
		'screen_reader_text' => __( 'Posts navigation', 'textdomain' ),
	) );
?>

get_the_posts_navigation()も同様ですが出力しないため、echoが必要になります。

標準のコードと出力されるHTML

the_posts_navigation()のデフォルト出力
<?php the_posts_navigation(); ?>
<nav class="navigation posts-navigation" role="navigation">
	<h2 class="screen-reader-text">投稿ナビゲーション</h2>
	<div class="nav-links">
		<div class="nav-previous"><a href="https://example.com/category/page/3/">過去の投稿</a></div>
		<div class="nav-next"><a href="https://example.com/category/">新しい投稿</a></div>
	</div>
</nav>

nextクラス側が新しい記事リストへのリンクになります。

装飾用CSSクラス

.posts-navigation {}
.posts-navigation .nav-links {}
.posts-navigation .nav-links .nav-previous {}
.posts-navigation .nav-links .nav-next {}

.navigation / .screen-reader-text / .nav-links これらのクラスは、他でも使われているため、単独で指定する場合は注意が必要です。

カスタマイズ例

※翻訳関数は省略しています・・・

サンプルで使っているCSS

.posts-navigation {
	display: table;
	width: 100%;
	padding: 8px 0;
	border-top: 1px solid #000;
	font-size: 1.4rem;
}
.posts-navigation .nav-links {
	display: table-row;
	width: 100%;
	word-break: break-all;
}
.posts-navigation .nav-links .nav-previous {
	display: table-cell;
	width: 50%;
	padding-right: 48px;
	text-align: left;
}
.posts-navigation .nav-links .nav-next {
	display: table-cell;
	width: 50%;
	padding-left: 48px;
	text-align: right;
}

表示文字列を変更する

文字の変更

<?php
	the_posts_navigation( array(
		'prev_text'     => '< 前のページへ',
		'next_text'     => '次のページへ >'
	) );
?>

htmlタグも使える

<?php
	the_posts_navigation( array(
		'prev_text'     => '<i class="fa fa-chevron-circle-left"></i>',
		'next_text'     => '<i class="fa fa-chevron-circle-right"></i>'
	) );
?>

前の○件 / 次の○件表示にする

個別の指定がない場合は基本的に、設定 > 表示設定 > 1ページに表示する最大投稿数で設定されている件数になります。

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

画像を指定する

<?php
	the_posts_navigation( array(
		'prev_text'     => '<img src="' . get_template_directory_uri() . '/images/arrow-left.png">',
		'next_text'     => '<img src="' . get_template_directory_uri() . '/images/arrow-right.png">',
	) );
?>

Codex

wp4.1までの方法

https://wpqw.jp/wordpress/themes/posts-link/