function taxonomy_build_node_index

taxonomy_build_node_index($node)

Builds and inserts taxonomy index entries for a given node.

The index lists all terms that are related to a given node entity, and is therefore maintained at the entity level.

Parameters

\Drupal\node\Entity\Node $node: The node entity.

Related topics

Taxonomy indexing
Functions to maintain taxonomy indexing.

File

core/modules/taxonomy/taxonomy.module, line 491
Enables the organization of content into categories.

Code

function taxonomy_build_node_index($node) {
  // We maintain a denormalized table of term/node relationships, containing
  // only data for current, published nodes.
  if (!\Drupal::config('taxonomy.settings')->get('maintain_index_table') || !(\Drupal::entityManager()->getStorage('node') instanceof SqlContentEntityStorage)) {
    return;
  }

  $status = $node->isPublished();
  $sticky = (int) $node->isSticky();
  // We only maintain the taxonomy index for published nodes.
  if ($status && $node->isDefaultRevision()) {
    // Collect a unique list of all the term IDs from all node fields.
    $tid_all = array();
    $entity_reference_class = 'Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem';
    foreach ($node->getFieldDefinitions() as $field) {
      $field_name = $field->getName();
      $class = $field->getItemDefinition()->getClass();
      $is_entity_reference_class = ($class === $entity_reference_class) || is_subclass_of($class, $entity_reference_class);
      if ($is_entity_reference_class && $field->getSetting('target_type') == 'taxonomy_term') {
        foreach ($node->getTranslationLanguages() as $language) {
          foreach ($node->getTranslation($language->getId())->$field_name as $item) {
            if (!$item->isEmpty()) {
              $tid_all[$item->target_id] = $item->target_id;
            }
          }
        }
      }
    }
    // Insert index entries for all the node's terms.
    if (!empty($tid_all)) {
      foreach ($tid_all as $tid) {
        db_merge('taxonomy_index')
          ->key(array('nid' => $node->id(), 'tid' => $tid, 'status' => $node->isPublished()))
          ->fields(array('sticky' => $sticky, 'created' => $node->getCreatedTime()))
          ->execute();
      }
    }
  }
}

© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!modules!taxonomy!taxonomy.module/function/taxonomy_build_node_index/8.1.x