Wordpress comment pagination : newest comments on first page

I use Wordpress commment pagination as follows:

  • paginated comments
  • comments displayed with the newest comments at the top of each page
  • 50 comments on each page
  • first page displayed by default

The problem is that I am trying to achieve YouTube like comments such as - newest comments on first page, first page being displayed by default, then older comments in order on page 2, 3 etc

The problem is that Wordpress comments are structured in such way,that I cannot achieve this by changing the "Discussion" settings.

I have tried different options, such as extending the Walker's paged_walk() function, or to reverse the comments, or even pulling the comments with a MySQL query and using paginate_link() - but can't seem to be able to achieve this type of comments hierarchy.

Any advice is appreciated, thank you!

Solution:

I have found a solution as follows:

  • into functions.php I have inserted a custom function that sorts the comments by date (newest comments first) by using an associative array sorting as can be seen here
  • into the Wordpress settings I changed the following at Settings -> Discussion Comments should be displayed with the comments at the top of each page

So now my comments are being displayed newest first (at top) with page numbering starting from 1.

The only issue that I see, is that when posting a comment the user is redirected for some reason to the last page of comments.

Topic pagination comments Wordpress

Category Web


add_action('pre_get_comments', function($query){
    if ( !is_admin()) {
        $query->query_vars['order'] = 'DESC';
    }
});

and set sorting in backend to oldest comments first in settings


A simple way to arrange your comments by most recent is to add this to your functions.php file:

if (!function_exists('custom_reverse_comments')) {
    function custom_reverse_comments($comments) {
        return array_reverse($comments);
    }   
}
add_filter ('comments_array', 'custom_reverse_comments');

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.