function comment_node_search_result

Same name in other branches
  1. 7.x modules/comment/comment.module \comment_node_search_result()
  2. 9 core/modules/comment/comment.module \comment_node_search_result()
  3. 8.9.x core/modules/comment/comment.module \comment_node_search_result()

Implements hook_node_search_result().

Formats a comment count string and returns it, for display with search results.

File

core/modules/comment/comment.module, line 424

Code

function comment_node_search_result(EntityInterface $node) {
    $comment_fields = \Drupal::service('comment.manager')->getFields('node');
    $comments = 0;
    $open = FALSE;
    foreach ($comment_fields as $field_name => $info) {
        // Skip fields that entity does not have.
        if (!$node->hasField($field_name)) {
            continue;
        }
        // Do not make a string if comments are hidden.
        $status = $node->get($field_name)->status;
        if (\Drupal::currentUser()->hasPermission('access comments') && $status != CommentItemInterface::HIDDEN) {
            if ($status == CommentItemInterface::OPEN) {
                // At least one comment field is open.
                $open = TRUE;
            }
            $comments += $node->get($field_name)->comment_count;
        }
    }
    // Do not make a string if there are no comment fields, or no comments exist
    // or all comment fields are hidden.
    if ($comments > 0 || $open) {
        return [
            'comment' => \Drupal::translation()->formatPlural($comments, '1 comment', '@count comments'),
        ];
    }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.