WordPressのページャー・ページネーションをプラグインを使用しないでを自作する方法をご紹介します。
※テンプレートファイルを直接編集する場合などは、必ずバックアップを取ってから編集してください。
また、利用する場合は自己責任でお願いします。
ページャーの出力を設定
functions.phpに記述します。
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | if ( !function_exists( 'pagination' ) ){ function pagination( $pages = '' , $range = 4){ $showitems = ( $range * 2)+1; global $paged ; //現在のページの値 if ( empty ( $paged ) ){ //デフォルトのページ $paged = 1; } if ( $pages == '' ){ global $wp_query ; $pages = $wp_query ->max_num_pages; //全ページ数を取得 if ( ! $pages ){ //全ページ数が空の場合は、1にする $pages = 1; } } if ( 1 != $pages ){ //全ページ数が1以外の場合は以下を出力する echo "<div class=\"pagination\"><span>Page " . $paged . " of " . $pages . "</span>" ; if ( $paged > 2 && $paged > $range +1 && $showitems < $pages ){ echo "<a href='" .get_pagenum_link(1). "'>« First</a>" ; } if ( $paged > 1 && $showitems < $pages ){ echo "<a href='" .get_pagenum_link( $paged - 1). "'>‹ Previous</a>" ; } for ( $i =1; $i <= $pages ; $i ++){ if (1 != $pages &&( !( $i >= $paged + $range +1 || $i <= $paged - $range -1) || $pages <= $showitems )){ echo ( $paged == $i )? "<span class=\"current\">" . $i . "</span>" : "<a href='" .get_pagenum_link( $i ). "' class=\"inactive\"" . $page_no_index . ">" . $i . "</a>" ; } } if ( $paged < $pages && $showitems < $pages ){ echo "<a href=\"" .get_pagenum_link( $paged + 1). "\">Next ›</a>" ; } if ( $paged < $pages -1 && $paged + $range -1 < $pages && $showitems < $pages ){ echo "<a href='" .get_pagenum_link( $pages ). "'>Last »</a>" ; } echo "</div>\n" ; } } } |
ページャーを出力
ページャーを出力するテンプレートファイル(index.php・category.phpなど)に以下を記述します。
01 02 03 | <?php if (function_exists( "pagination" )) { pagination( $wp_query ->max_num_pages); } ?> |
出力されるコード
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 | < div class = "pagination" > < span >Page 6 of 30</ span > < span class = "current" >6</ span > </ div > |
新たにID名・クラス名を追記や変更する場合は、function.phpに記述している内容が出力されますので、自分好みに変更してみてください。
あとは、cssなどで編集すればデザインの幅が広がりますよね。
※functions.phpを編集する場合は必ずバックアップを取ってから行ってくださいね。