我想建立一个页面,显示所有评论,无论它们附在哪个帖子上。我还希望该页面被分页,因为它可能有10000多条评论。
我不知道该怎么做,但以下是我迄今为止研究过的一些函数:
-
get_comments
-如果没有传入post_id
,它将返回所有注释。然而,我看不到对这些进行分页的方法(有offset
和number
选项可供选择,但手动操作非常繁琐)。 -
wp_list_comments
-关于这方面的文档非常糟糕,但源代码建议,如果与get_comments
一起使用,我们可以通过传递get_comments
数组作为第二个参数来循环所有注释。然而,这仍然会使用get_comments
来实际。。。好吧,得到评论,似乎没有办法对此进行宣传。 -
previous_comments_link
&next_comments_link
-这些似乎只与wp_list_comments
一起工作(没有第二个自变量)。 -
paginate_comments_links
-看起来它只适用于wp_list_comments
(没有第二个参数)。
我尝试过的:
-
在
get_comments
:中简单使用number
自变量$comments = get_comments(array( 'status' => 'approve', 'number' => '2' )); wp_list_comments(array( 'callback' => 'my_rendering_function' ), $comments); paginate_comments_links();
这不会显示任何分页链接。
-
这里建议的方法是:在带有分页的页面上显示最新评论
$comments = get_comments(array( 'status' => 'approve' )); wp_list_comments('per_page=2', $comments); paginate_comments_links();
这两者都不起作用(它显示了前2条注释,但没有分页)。此外,我对
get_comments
将所有注释加载到内存中感到尴尬。
问题:
如何对所有评论进行分页?
附言我正在使用WordPress 3.4.1&PHP 5.3.2。
如果你计划建立自己的分页,你需要知道你将要使用的注释总数,因此你必须加载所有注释。
我已经建立了我想要使用的东西,如果它有帮助,请告诉我。
#Config here.
define('DEFAULT_COMMENTS_PER_PAGE',100);
$page = (int) (!isset($_REQUEST["page"]) ? 1 : $_REQUEST["page"]);
$limit = DEFAULT_COMMENTS_PER_PAGE;
$offset = ($page * $limit) - $limit;
$param = array(
'status'=>'approve',
'offset'=>$offset,
'number'=>$limit,
);
$total_comments = get_comments(array('status'=>'approve'));
$pages = ceil(count($total_comments)/DEFAULT_COMMENTS_PER_PAGE);
$comments = get_comments($param);
foreach($comments as $comment) {
// ECHO THE AUTHOR AND COMMENT
echo("<strong>{$comment->comment_author}</strong> - {$comment->comment_content}");
}
$args = array(
'base' => 'https://example.com/all-comments/%_%',
'format' => '?page=%#%',
'total' => $pages,
'current' => $page,
'show_all' => False,
'end_size' => 1,
'mid_size' => 2,
'prev_next' => True,
'prev_text' => __('« Previous'),
'next_text' => __('Next »'),
'type' => 'plain');
// ECHO THE PAGENATION
echo paginate_links( $args );
我们应该担心使用get_comments()来获取总注释的性能。必须使用参数偏移量为false,计数为true,如下所示:
$comments_per_page = 2;
$page = 2;
//MYSQL: LIMIT offset, number
$params = array(
'post_id' => $post_id,
'offset' => (--$page) * $comments_per_page,
'number' => $comments_per_page,
);
$comments = get_comments( $params );
$total_comments = get_comments(
array_merge($params,
array(
'count' => true,
'offset' => 0,
'number' => 0
)
)
);
$args = array(
'total' => ceil( $total_comments / $comments_per_page ),
'current' => max( 1, $page ),
);
$pagination = paginate_links( $args );
添加您需要的任何参数。您可以使用wp_list_comments()作为weel,但如果您想自定义输出HTML,请使用foreach作为$comments:
foreach ( $comments as $comment ) :
echo $comment->comment_date;
echo '<br>';
echo $comment->comment_author;
echo '<br>';
echo $comment->comment_content;
endforeach;