8
8

More than 3 years have passed since last update.

Wordpressでページネーション実装する一番簡単な方法

Posted at

Wordpressの一覧ページでプラグインを使わずにページネーションを実装する方法。

具体的なパラメータなどはcodex参照。
paginate_links()

一覧ページでページネーション

リストを出力する

  • funciotns.phpに以下の関数を追記し、テンプレートで呼び出し
  • 関数の部分を直接テンプレート側に記述してもOK
// functions.php
function the_pagination() {
  // 一覧ページのクエリ
  global $wp_query;
  // ありそうもない数字をセット
  $big = 999999999;
  // 1ページ以下なら非表示
  if ( $wp_query->max_num_pages <= 1 ) return;
  echo paginate_links( array(
    'base'         => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
    'format'       => '?paged=%#%',
    'current'      => max( 1, get_query_var('paged') ),
    'total'        => $wp_query->max_num_pages,
    'type'         => 'list',
    'end_size'     => 2,
    'mid_size'     => 2
  ) );
}

// index.php
<?php if( function_exists("the_pagination") ) the_pagination(); ?>

ページネーションでulやliタグをカスタマイズする

  • 上の方法だとHTMLタグ変えられないのでClassの変更とかしたい場合はこちら
  • typeをarrayにするとaタグの配列を取得できるのでPHPで表示する
// functions.php
function the_pagination() {
  // 一覧ページのクエリ
  global $wp_query;
  // ありそうもない数字をセット
  $big = 999999999;
  // 1ページ以下なら非表示
  if ( $wp_query->max_num_pages <= 1 ) return;
  return paginate_links( array(
    'base'         => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
    'format'       => '?paged=%#%',
    'current'      => max( 1, get_query_var('paged') ),
    'total'        => $wp_query->max_num_pages,
    'type'         => 'array',  // arrayに変更
    'end_size'     => 2,
    'mid_size'     => 2
  ) );
}
// index.php
<?php 
if( function_exists("the_pagination") ) {
  $pagination_array = the_pagination();
  // 配列じゃないなら非表示
  if ( !is_array($pagination_array) ) return;
  echo '<ul class="nav pagination">';
  foreach($pagination_array as $key => $val) {
    echo '<li class="item">'.$pagination_array[$key].'</li>';
  }
  echo '</ul>';
}

?>
8
8
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
8
8