Exclude entities which have a redirect from the search api index
03/09/2018 14:27
For a custom project, we use a taxonomy to tag nodes. Some terms have their own page, while others redirect to a node. The search on the site has one index which contains both nodes and terms, but the terms which are redirecting shouldn't show up when viewing a search results page. While it's possible to use hook_search_api_index_items_alter(), a nicer way to exclude them is by using a processor plugin so you can enable them in the UI per index. The relevant code is underneath. Adjust to your own likings - and maybe inject the service if you want to as well :)
<?phpnamespace Drupal\project\Plugin\search_api\processor;use Drupal\search_api\IndexInterface;use Drupal\search_api\Processor\ProcessorPluginBase;/** * Excludes entities which have a redirect. * * @SearchApiProcessor( * id = "entity_redirect", * label = @Translation("Entity redirect"), * description = @Translation("Exclude entities which have a redirect from being indexed."), * stages = { * "alter_items" = 0, * }, * ) */class EntityRedirect extends ProcessorPluginBase { /** * {@inheritdoc} */ public static function supportsIndex(IndexInterface $index) { foreach ($index->getDatasources() as $datasource) { $entity_type_id = $datasource->getEntityTypeId(); if (!$entity_type_id) { continue; } if ($entity_type_id === 'node' || $entity_type_id == 'taxonomy_term') { return TRUE; } } return FALSE; } /** * {@inheritdoc} */ public function alterIndexedItems(array &$items) { $repository = \Drupal::service('redirect.repository'); $pathAliasmanager = \Drupal::service('path.alias_manager'); /** @var \Drupal\search_api\Item\ItemInterface $item */ foreach ($items as $item_id => $item) { $object = $item->getOriginalObject()->getValue(); try { $path = $object->toUrl()->toString(); $path = $pathAliasmanager->getPathByAlias($path); $path = ltrim($path, '/'); $redirect = $repository->findMatchingRedirect($path); if (!empty($redirect)) { unset($items[$item_id]); } } catch (\Exception $ignored) {} } }}?>
Exclude entities which have a redirect from the search api index: https://realize.be/blog/exclude-entities-which-have-redirect-search-api-index