David Lohmeyer's Blog

Reverse core threaded comment ordering in Drupal 8!

The default ordering of all comments in Drupal 8's core comment module is ascending, meaning the oldest comments are displayed first. Sometimes you don't want this.

Assuming your comment field's machine name is field_comments, put this code into a module to get descending comments. I was having trouble with threaded comments, but this works since it alters the query by the c.thread database column instead of just 'torder':

 * Implements hook_query_TAG_alter() for comment_filter tag.
 * @see CommentStorage::loadThread().
function MYMODULE_query_comment_filter_alter(Drupal\Core\Database\Query\AlterableInterface $query) {
  // Change comment order to DESC for 'comment' field.
  if ($query->getMetaData('field_name') == 'field_comments') {

    $order_by = &$query->getOrderBy();
    $expressions = &$query->getExpressions();
    // Sorting for threaded comments.
    if (isset($order_by['torder']) && $order_by['torder'] == 'ASC') {
      // Get rid of the expressions that prepare the threads for ASC ordering.
      // Simply order by the thread field.
      $order_by['c.thread'] = 'DESC';




Related Posts