1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

WordPress のページネーションで Prev/Next (戻る/進む) を常時表示させる

Last updated at Posted at 2025-02-23

はじめに

WordPress には the_posts_pagination を呼び出すことでページネーションを表示することができる。

<?php the_posts_pagination([ /* 条件を配列で指定 */ ]); ?>

何も手を加えず標準のページネーションを表示させると、次ページ(前ページ)が存在しないと Prev/Next (戻る/進む) が表示されない仕様になっている。
個人的には Prev/Next (戻る/進む) ボタンは disable で表示されているべきだと考えているので function.php に1つ処理を書いて表示させるようにする。

navigation_markup_template を定義する

ページネーションの処理を一部変更するには navigation_markup_template の定義を上書きしてあげることで対応可能。
WordPress 側の関連するコードは以下を参照してほしい。

元の ページネーション表示の定義は以下のようになっている。

src/wp-includes/link-template.php
	$template = '
	<nav class="navigation %1$s" aria-label="%4$s">
		<h2 class="screen-reader-text">%2$s</h2>
		<div class="nav-links">%3$s</div>
	</nav>';

<div class="nav-links">%3$s</div> の前後に 戻るボタン用の処理、進むボタン用の処理それぞれを追加してあげれば良い。
実際に functions.php に記載するコードは以下のようになる。

functions.php
add_filter('navigation_markup_template', function ($template, $class) {
    global $wp_query;
    $total   = isset($wp_query->max_num_pages) ? $wp_query->max_num_pages : 1;
    $current = get_query_var('paged') ? (int) get_query_var('paged') : 1;
    $first = $last = '';

    if ($current == 1) {
        $first = '<span class="prev page-numbers inactive">' . _x('Previous', 'previous set of posts') .  '</span>';
    }
    if ($current == $total) {
        $last = '<span class="next page-numbers inactive">'. _x('Next', 'next set of posts') .'</span>';
    }


    $template = '
    <nav class="navigation %1$s" role="navigation" aria-label="%4$s">
        <h2 class="screen-reader-text">%2$s</h2>
        <div class="nav-links">
        '.$first.'
        %3$s
        '.$last.'
        </div>
    </nav>';
    return $template;
}, 10, 2);

Ref

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?