前後移動のページネーションを実装する

WordPressで前後移動のみの簡単なページネーションを実装する方法をメモしておきます。

一覧ページ

一覧ページではprevious_posts_link()とnext_posts_link()を使用します。

PHP

<div class="pager">
  <div class="pager-prev"><?php previous_posts_link('前のページ'); ?></div>
  <div class="pager-next"><?php next_posts_link('次のページ'); ?></div>
</div>

HTMLでの出力は以下のようになります。

1ページ目

<div class="pager">
  <div class="pager-prev"></div>
  <div class="pager-next"><a href="http://xxxxx/archive/page/2/" >次のページ</a></div>
</div>

2ページ目

<div class="pager">
  <div class="pager-prev"><a href="http://xxxxx/archive/" >前のページ</a></div>
  <div class="pager-next"><a href="http://xxxxx/archive/page/3/" >次のページ</a></div>
</div>

3ページ目(最終ページ)

<div class="pager">
  <div class="pager-prev"><a href="http://xxxxx/archive/page/2/" >前のページ</a></div>
  <div class="pager-next"></div>
</div>

 

個別ページ

個別ページではprevious_post_link()とnext_post_link()を使用します。
一覧ページは「posts」で個別ページは「post」と微妙に違うので注意してください。

PHP

<div class="pager">
  <div class="pager-prev"><?php previous_post_link('%link', '前の記事'); ?></div>
  <div class="pager-next"><?php next_post_link('%link', '次の記事'); ?></div>
</div>

HTMLでの出力は以下のようになります。

最新の記事

<div class="pager">
  <div class="pager-prev"><a href="http://xxxxx/single02/" rel="prev">前の記事</a></div>
  <div class="pager-next"></div>
</div>

2番目の記事

<div class="pager">
  <div class="pager-prev"><a href="http://xxxxx/single01/" rel="prev">前の記事</a></div>
  <div class="pager-next"><a href="http://xxxxx/single03/" rel="next">次の記事</a></div>
</div>

3番目の記事(最後の記事)

<div class="pager">
  <div class="pager-prev"></div>
  <div class="pager-next"><a href="http://xxxxx/single02/" rel="next">次の記事</a></div>
</div>

記事がない場合にタグを出力しないようにしたい場合、get_previous_post()とget_next_post()を使って判定します。

PHP

<div class="pager">
  <?php if (get_previous_post()):?>
    <div class="pager-prev"><?php previous_post_link('%link', '前の記事'); ?></div>
  <?php endif; ?>
  <?php if (get_next_post()):?>
    <div class="pager-next"><?php next_post_link('%link', '次の記事'); ?></div>
  <?php endif; ?>
</div>

HTMLでの出力は以下のようになります。

最新の記事

<div class="pager">
  <div class="pager-prev"><a href="http://xxxxx/news/single02/" rel="prev">前の記事</a></div>
</div>

2番目の記事

<div class="pager">
  <div class="pager-prev"><a href="http://xxxxx/news/single01/" rel="prev">前の記事</a></div>
  <div class="pager-next"><a href="http://xxxxx/news/single03/" rel="next">次の記事</a></div>
</div>

3番目の記事(最後の記事)

<div class="pager">
  <div class="pager-next"><a href="http://xxxxx/news/single02/" rel="next">次の記事</a></div>
</div>

 

【参考サイト】

 

このエントリーをはてなブックマークに追加

関連記事

コメントを残す

メールアドレスが公開されることはありません。
* が付いている欄は必須項目です

CAPTCHA


コメントが承認されるまで時間がかかります。

2024年4月
 123456
78910111213
14151617181920
21222324252627
282930