網路上有非常多WordPress分頁頁碼的方法,寫得都非常好,都是有用的,但既然用WordPress我想儘可能地使用接近WordPress API的方法,用核心方法,當然還是要越簡單越好,
paginate_links( string|array $args = ” )
預設參數:
<?php $args = array( 'base' => '%_%', 'format' => '?paged=%#%', 'total' => 1, 'current' => 0, 'show_all' => false, 'end_size' => 1, 'mid_size' => 2, 'prev_next' => true, 'prev_text' => __('« Previous'), 'next_text' => __('Next »'), 'type' => 'plain', //輸出格式 'add_args' => false, 'add_fragment' => '', 'before_page_number' => '', 'after_page_number' => '' ); ?>
輸出格式分為三種:
- 頁碼輸出為陣列
- 頁碼輸出列表 (推薦)
- 預設
頁碼輸出為陣列:
輸出為陣列(Array)型態,可供開發者進一步處理然後輸出,自由度最高的一種方式。
帶入參數:type = ‘array’
<?php $links = paginate_links( array( 'type' => 'array' ) ); echo '<div class="pagination col-6">'; foreach( $links as $link ){ echo $link; } echo '</div>'; ?>
輸出:
Array ( [0] => <span class='page-numbers current'>1</span> [1] => <a class='page-numbers' href='http://localhost/page/2/'>2</a> [2] => <a class='page-numbers' href='http://localhost/page/3/'>3</a> [3] => <span class="page-numbers dots">…</span> [4] => <a class='page-numbers' href='http://localhost/page/10/'>10</a> [5] => <a class="next page-numbers" href="http://localhost/page/2/">Next »</a> )
頁碼輸出為列表(推薦):
輸出為帶有html常用的<ul><li>的清單結構字串,這就很適合用來當頁碼使用,代碼非常簡短。
帶入參數:type = ‘list’
<?php echo paginate_links( array( 'type' => 'list' ) ); ?>
輸出:
<ul class='page-numbers'> <li><span class='page-numbers current'>1</span></li> <li><a class='page-numbers' href='http://locahost/page/2/'>2</a></li> <li><a class='page-numbers' href='http://localhost/page/3/'>3</a></li> <li><span class="page-numbers dots">…</span></li> <li><a class='page-numbers' href='http://localhost/page/10/'>10</a></li> <li><a class="next page-numbers" href="http://localhost/page/2/">Next »</a></li> </ul>
可套用下列CSS範本:
/* WP 頁碼 style v123.tw */ ul.page-numbers { margin:0 auto; overflow:hidden; } ul.page-numbers li{ list-style: none; float:left; margin: 0 .2em; } ul.page-numbers .page-numbers { text-decoration:none; display:inline-block; font-size: 1em; margin:0; padding: 0 .5em; cursor: pointer; color: #949494; border: 1px solid #949494; } ul.page-numbers .page-numbers.current, ul.page-numbers li:hover .page-numbers { background-color: #b2b2b2; color: #fff; }
頁碼輸出為預設:
基本上是把第一種陣列輸出的方式的值,輸出為字串,可供開發者加以運用
帶入參數:type = ” | NULL
<?php echo paginate_links( array( 'type' => '' ) ); ?>
輸出:
<span class='page-numbers current'>1</span> <a class='page-numbers' href='http://localhost/page/2/'>2</a> <a class='page-numbers' href='http://localhost/page/3/'>3</a> <span class="page-numbers dots">…</span> <a class='page-numbers' href='http://localhost/page/10/'>10</a> <a class="next page-numbers" href="http://localhost/page/2/">Next »</a>