如何利用WordPress函数生成Bootstrap4分页呢?因为wordpress默认仅仅提供简单分页, 所以要实现数字分页,需要自定义函数,wordpress可以结合bootstrap制作分页,bootstrap提供了分页的样式,可以减少对样式的书写。
我们先看下 Bootstrap4
默认的分页结构
<nav aria-label="Page navigation example">
<ul class="pagination">
<li class="page-item">
<a class="page-link" href="#">Previous</a>
</li>
<li class="page-item">
<a class="page-link" href="#">1</a>
</li>
<li class="page-item">
<a class="page-link" href="#">2</a>
</li>
<li class="page-item">
<a class="page-link" href="#">3</a>
</li>
<li class="page-item">
<a class="page-link" href="#">Next</a>
</li>
</ul>
</nav>
根据以上结构,我们构建一个函数,并放到 function.php
中。
<?php
/**
* WordPress适配Bootstrap4 之 分页
* http://www.inli.work/wordpress-adapter-bootstrap4-paging.html
*/
function ribs_pagenavi($before = '', $after = '', $p = 1) {
if (is_singular()) return;
global $wp_query, $paged;
$max_page = $wp_query->max_num_pages;
if ($max_page <= 1) return;
if (empty($paged)) $paged = 1;
echo $before . '<ul class="pagination mb-0">' . "\n";
if ($paged == 1) echo '<li class="page-item disable prev"><a class="page-link">上一页</a></li>';
//if ( $paged > 1 ) p_link( $paged - 1, '上页', '上页' );
if ($paged > 1) echo "<li class='page-item prev'><a class='page-link' href='", esc_html(get_pagenum_link($paged - 1)), "' title='上一页'>上一页</a></li>";
if ($paged > $p + 1) p_link(1, '首页');
if ($paged > $p + 2) echo '<li class="page-item disable"><a class="page-link">...</a></li>';
for ($i = $paged - $p;$i <= $paged + $p;$i++) {
if ($i > 0 && $i <= $max_page) $i == $paged ? print "<li class='page-item active'><span class='page-link'>{$i}<span class='sr-only'>(current)</span></span></li>" : p_link($i);
}
if ($paged < $max_page - $p - 1) echo '<li class="page-item disable"><a class="page-link">...</a></li>';
if ($paged < $max_page - $p) p_link($max_page, '尾页');
//if ( $paged < $max_page ) p_link( $paged + 1,'下页', '下页' );
if ($paged < $max_page) echo "<li class='page-item next'><a class='page-link' href='", esc_html(get_pagenum_link($paged + 1)), "' title='下一页'>下一页</a></li>";
if ($paged == $max_page) echo '<li class="page-item disable next"><a class="page-link">下一页</a></li>';
echo '</ul>' . $after . "\n";
}
function p_link($i, $title = '', $linktype = '') {
if ($title == '') $title = "第 {$i} 页";
if ($linktype == '') {
$linktext = $i;
} else {
$linktext = $linktype;
}
echo "<li class='page-item'><a class='page-link' href='", esc_html(get_pagenum_link($i)), "' title='{$title}'>{$linktext}</a></li>";
}
最后在需要分页的地方,引用
<?php ribs_pagenavi('<nav class="post-pagenavi my-5">', '</nav>', 1); ?>