我想构建一个页面来显示所有评论,无论它们附加到哪个帖子。我还希望对该页面进行分页,因为它可能有 10,000 多条评论。
我不确定该怎么做,但这是我目前研究过的一些函数:
get_comments
- 如果没有传入post_id
,它将返回所有评论。但是,我看不到对这些进行分页的方法(有offset
和number
选项可供摆弄,但这样做非常乏味手动)。wp_list_comments
- 这方面的文档非常糟糕,但是 the source code建议如果与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();
这不会显示任何分页链接。
此处建议的方法:Display latest comments on page with pagination
$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 );
关于php - Wordpress 独立评论页面 - 带分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12241339/