使用WordPress的朋友都知道,它的分页采用的是“上一页、下一页”的方式,对于文章太多的朋友不是太方面,当然你可以使用一些翻页的插件来实现如 “pages:1 of 10 1 2 3 4 …”的效果,本人一直都不太喜欢使用插件,正好手头有个不错的方法来实现。
1. 打开你主题模板的functions.php,在里面添加以下代码:
<?php
function wp_pagenavi($before = '', $after = '', $prelabel = '', $nxtlabel = '', $pages_to_show = 5, $always_show = false){
global $request, $posts_per_page, $wpdb, $paged;
if (empty($prelabel)) {
$prelabel = '<strong>上一页</strong>';
}
if (empty($nxtlabel)) {
$nxtlabel = '<strong>下一页</strong>';
}
$half_pages_to_show = round($pages_to_show / 2);
if (!is_single()) {
if (!is_category()) {
preg_match('#FROM\\s(.*)\\sORDER BY#siU', $request, $matches);
} else {
preg_match('#FROM\\s(.*)\\sGROUP BY#siU', $request, $matches);
}
$fromwhere = $matches[1];
$numposts = $wpdb->get_var("SELECT COUNT(DISTINCT ID) FROM {$fromwhere}");
$max_page = ceil($numposts / $posts_per_page);
if (empty($paged)) {
$paged = 1;
}
if ($max_page > 1 || $always_show) {
echo "{$before} <div class='pagers'><span>当前第 {$paged} / {$max_page} 页 : </span>";
if ($paged >= $pages_to_show - 1) {
echo '<a href="' . get_pagenum_link() . '">« 首页</a>';
}
previous_posts_link($prelabel);
for ($i = $paged - $half_pages_to_show; $i <= $paged + $half_pages_to_show; $i++) {
if ($i >= 1 && $i <= $max_page) {
if ($i == $paged) {
echo "<strong>{$i}</strong>";
} else {
echo '<a href="' . get_pagenum_link($i) . '">' . $i . '</a>';
}
}
}
next_posts_link($nxtlabel, $max_page);
if ($paged + $half_pages_to_show < $max_page) {
echo '<a href="' . get_pagenum_link($max_page) . '">最后 »</a>';
}
echo "</div> {$after}";
}
}
}?>
2. 在index.php archive.php等需要分页的地方使用
<?php wp_pagenavi(); ?>
替换掉
<?php previous_post_link('上一篇: %link'); ?>
<?php next_post_link('%link :下一篇'); ?>
CSS样式
.pagers{height:25px;color:#111;padding:2px 0;margin:0;text-align:center;}
.pagers a,.pagers strong{margin:0 2px;padding:2px 5px;}
.pagers a{border:1px solid #6c8c37}
.pagers strong{border:1px solid #111}