原文链接:
http://www.wavemood.net/create_all_comments_page_3.html
复制过来有点混乱
本文涉及的文件:
all-comments.php — 页面模板(请根据自己使用的主题编写)
all-comment-template.php — 评论模板
all-comment-function.php — 分页函数
all-comment-navi.css — 分页条样式
点此下载
我们将建立一个带有分页功能的留言板。
没有看过的朋友可以回顾
建立一个显示所有评论的留言板 I
建立一个显示所有评论的留言板 II
1. 先来了解下分页的基本原理。
在
建立一个显示所有评论的留言板 II中用到的SQL,取出了数据库中所有的评论,如果可以根据我们的要求,每次只取出我们需要的部分,就可以实现分页了。
如果想从Mysql数据库中取出连续的部分数据,可以使用“
limit”参数,看下面的例子:
select * from table limit 30, 10;
这句SQL的意思是:从table表中取出第31条~第40条数据。
我们只需要定义数据的起点和数据长度,就能得到我们需要的数据段。
2. 分页的实现
Q: 如何得到当前的页码?
A: 当我们点击导航条的时候,页码通过
?page=2这样的参数传递回页面,在PHP中通过
$_GET['page']来获得。
Q: 如何计算数据的起点?
A: limit的第一个参数是数据的起点,通过公式“
$offset = 每页显示的数量 * (当前页码 - 1)”来计算。
有了这样的知识,就可以开工了。
重新编辑all-comment-template.php
<?php
global $wpdb, $comment, $wp_query;
$num_per_page = 20; // 每页显示
$page_now = $_GET['page'];
// 参数验证
if (!isset($num_per_page) || !is_numeric($num_per_page) || $num_per_page < 1) {
$num_per_page = 1;
}
if (!isset($page_now) || !is_numeric($page_now) || $page_now < 1) {
$page_now = 1;
}
// 获取总页数
$query = "select count(*) from $wpdb->posts AS posts, $wpdb->comments AS comments
where posts.ID = comments.comment_post_ID
and posts.post_status = 'publish'
and comments.comment_approved = '1'
and comments.comment_type = ''";
$wp_query->comment_count = $count = $wpdb->get_var($query);
$max_page = ceil($count / $num_per_page);
if ($page_now > $max_page) {
$page_now = 1;
}
// 获取offset
$offset = $num_per_page * ($page_now - 1);
// 获取点评
$query = "select posts.*, comments.*
from $wpdb->posts as posts, $wpdb->comments as comments
where posts.ID = comments.comment_post_ID
and posts.post_status = 'publish'
and comments.comment_approved = '1'
and comments.comment_type = ''
order by comment_date desc
limit $offset, $num_per_page";
$comments = $wpdb->get_results($wpdb->prepare($query));
// 输出分页
for($i=1; $i<=$max_page; $i++) {
echo '<span style="width:20px;"><a href="?page=' . $i . '">' . $i . '</a></span>';
}
// 如果你愿意,可以美化分页信息
// 使用下面的语句输出一个类似postnavi的分页条,来代替上面的for语句
// 所需的文件在本文开头已经给出
// $css_url = get_bloginfo("template_url") . "/all-comment-navi.css";
// echo "\n" . '<link rel="stylesheet" href="' . $css_url . '" type="text/css" media="screen" />';
// $function_url = "all-comment-function.php";
// require($function_url);
// echo get_ecnavi($max_page, $page_now, 5, $count);
// 调用显示comments
define('COMMENTS_TEMPLATE', true);
$include = apply_filters
('comments_template', TEMPLATEPATH
. '/comments.php' );
if (file_exists( $include ) )
require( $include );
else
require( WP_CONTENT_DIR
. '/themes/default/comments.php');
?>
[
本帖最后由 命运的阳光 于 2008-8-2 00:21 编辑 ]