Skip to main content
Drupal API
User account menu
  • Log in

Breadcrumb

  1. Drupal Core 11.1.x
  2. CommentHooks.php

function CommentHooks::nodeSearchResult

Implements hook_node_search_result().

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

File

core/modules/comment/src/Hook/CommentHooks.php, line 397

Class

CommentHooks
Hook implementations for comment.

Namespace

Drupal\comment\Hook

Code

public function nodeSearchResult(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'),
        ];
    }
}

API Navigation

  • Drupal Core 11.1.x
  • Topics
  • Classes
  • Functions
  • Constants
  • Globals
  • Files
  • Namespaces
  • Deprecated
  • Services
RSS feed
Powered by Drupal