Last comment page first with full number of comments?

This is indeed the default behavior of WordPress. The comments always stay on the same comment page, so if you show the last comment page first, that last comment page will not always have the “full” number of comments. The advantage of keeping a comment always on the same comment page is that the URL always stays the same, otherwise a comment can move to another page when new comments are added.

But it’s annoying, and I needed a workaround for this too. I found no (easy?) way to do this with WordPress hooks, so I sliced the comment array myself, by reading the cpage (comment page) query variable. Watch out with this variable, because WordPress will be so helpful to reverse it for you when you set the “first/last comment page first” to “last”.

This code goes in the comments.php theme file, because it reads the global variable $comments. I did not use a comment callback (it was very simple code), but you can still pass the newly sliced $comments_to_display array to wp_list_comments() as the second argument, it will use that instead of all comments then. I don’t know how this will work with threaded comments (how do they work with “normal” paged comments?).

$comments_to_display = $comments;

/*
 * Display the comments over pages, with the newest comments on the first page
 * Special in this code (not in WP by default) is that the first page will contain 5 comments,
 * and the final page can contain less comments.
 */
$comments_per_page = 5; // MAYBE: use get_option()?
$comment_page = get_query_var( 'cpage' );
$comment_this_page_start = 0;
$comment_this_page_count = $comments_per_page;
$oldest_comment_page_count = count( $comments_to_display ) % $comments_per_page;
if ( 0 == $oldest_comment_page_count ) {
    $oldest_comment_page_count = $comments_per_page;
}
if ( 1 == $comment_page ) {
    $comment_this_page_count = $oldest_comment_page_count;
} else {
    $comment_this_page_start = $oldest_comment_page_count + ($comment_page - 2) * $comments_per_page;
}
$comments_to_display = array_slice( $comments_to_display, $comment_this_page_start, $comment_this_page_count );
// You probably want to array_reverse() $comments_to_display, currently it shows the oldest on top.
// Then you should be able to pass $comments_to_display to wp_list_comments() and it will use your shorter array instead.

Leave a Comment