WP_Comment_Query is the WordPress class used to query comments. Once you understand its basic arguments, you can build custom comment lists in many different ways. In this article we will use it to build a paginated comment list.
Step 1: prepare the data required for comment pagination
You need three main values for pagination: the total number of comments, the number of comments shown on each page, and the current page number.
$user = wizhi_get_current_user();
// Use a custom query argument so it does not conflict with post pagination.
$paged = isset($_GET['cmpage']) ? $_GET['cmpage'] : 1;
$total = get_user_comments_count($user->ID);
$number = 6;
$offset = ($paged - 1) * $number;
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query(array(
'user_id' => $user->ID,
'number' => $number,
'offset' => $offset,
));
Step 2: output the queried comments
The actual comment list can include anything you want, such as the avatar, author name, or post title. For simplicity, this example only prints the comment content.
if ($comments) {
foreach ($comments as $comment) {
echo $comment->comment_content;
}
}
Step 3: print the pagination links
Once the comments are displayed, you can print either a simple next-page link or a numeric set of pagination links.
Display only a next-page link
If you do not need full numeric pagination, a single “next page” link is enough. The logic for the previous page works the same way.
if ($number == $current_count) {
echo '<a class="button" href="?tab=reply&cmpage=' . ($paged + 1) . '">Next Page</a>';
}
Display numeric pagination links
If you want numbered pagination, use WordPress’ paginate_links() function. The setup is almost the same as custom pagination for posts or users.
$current_page = max(1, $paged);
$max_num_pages = intval($total / $number) + 1;
echo paginate_links(array(
'base' => get_permalink($pid) . '%_%',
'format' => '?cmpage=%#%',
'current' => $current_page,
'total' => $max_num_pages,
));
Pagination in WordPress is usually simpler than it first appears. The query classes already support the parameters you need, so most of the work is just preparing the right values.
