纯代码实现Thesis主题分页导航功能

前在【如何在Thesis主题中启用WP-PageNavi插件】一文中介绍了使用WP-PageNavi插件替换Thesis主题默认的导航,实现效果很好。然而笔者今天突然嫌插件多了影响速度,欲除去WP-PageNavi插件。于是Google了半天,终于找到了完美解决方案:舍弃WP-PageNavi插件,纯代码实现Thesis主题分页导航功能。先放上效果图:

custompagenavi

纯代码实现分页导航功能

将以下代码插入custom_functions.php文件:

function numbered_page_nav($prelabel = '', $nxtlabel = '', $pages_to_show = 8, $always_show = false) {
	global $request, $posts_per_page, $wpdb, $paged;

	$custom_range = 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);
		}
		$blog_post_count = $matches[1];
		$numposts = $wpdb->get_var("SELECT COUNT(DISTINCT ID) FROM $blog_post_count");
		$max_page = ceil($numposts /$posts_per_page);
		if(empty($paged)) {
			$paged = 1;
		}
		if($max_page > 1 || $always_show) {
			echo "<div class='page-nav'><div class='page-nav-intro'>Page $paged of $max_page</div>";
			if ($paged >= ($pages_to_show-2)) {
				echo '<div><a href="'.get_pagenum_link().'">1</a></div><div>...</div>';
			}
			for($i = $paged - $custom_range; $i <= $paged + $custom_range; $i++) {
				if ($i >= 1 && $i <= $max_page) {
					if($i == $paged) {
						echo "<div class='current-page-number'>$i</div>";
					}
					else {
						echo '<div><a href="'.get_pagenum_link($i).'">'.$i.'</a></div>';
					}
				}
			}
			if (($paged+$custom_range) < ($max_page)) {
				echo '<div>...</div><div><a href="'.get_pagenum_link($max_page).'">'.$max_page.'</a></div>';
			}
			echo "</div>";
		}
	}
}
remove_action('thesis_hook_after_content', 'thesis_post_navigation');
add_action('thesis_hook_after_content', 'numbered_page_nav');

上面这段代码的功能就是替换掉Thesis主题默认的导航功能,接下来往custom.css文件中加入以下css代码,美化分页导航功能:

.page-nav { font-size: 1.35em; font-weight: bold; margin: 1em 0; padding: 0; overflow: hidden; }
.page-nav-intro { float: left; padding: .3em .5em; margin: 0 1em 1em 0; background: #efefef; border: .1em solid #ccc; }
.page-number { float: left; padding: .3em .5em; margin: 0 .2em; background: #fff; border: .1em solid #ccc;  }
.current-page-number { float: left; padding: .3em .5em; margin: 0 .2em; background: #efefef; border: .1em solid #ccc; }
.elipses { float: left; padding: .3em .2em; }

实现的分页导航效果和WP-PageNavi插件几乎一样。当然,CSS样式可以根据自己的Thesis主题风格修改。

Leave a Reply

Your email address will not be published. Required fields are marked *