Created
May 5, 2016 00:28
-
-
Save jonpugh/ccaeb01e173abbc6c88f7a332d271e4a to your computer and use it in GitHub Desktop.
Add Taxonomy Term to a Node's Breadcrumb in Drupal 8
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# modulename.services.yml | |
services: | |
modulename.breadcrumbs: | |
class: Drupal\modulename\Breadcrumbs | |
tags: | |
- { name: breadcrumb_builder, priority: 100 } |
Thank you all, here is a slightly more parametrized theme code version for non-node entities with taxonomy parents:
/**
* Implements hook_system_breadcrumb_alter().
*/
function THEMENAME_preprocess_breadcrumb(array &$vars) {
// proper taxonomy breadcrumbs for Commerce Products through field_category
$entity_type = 'commerce_product'; // TODO: change or verify
$taxonomy_field_name = 'field_category'; // TODO: change or verify
if (($entity = \Drupal::routeMatch()->getParameter($entity_type)) && $vars['breadcrumb']) {
$cache_tag = "{$entity_type}:{$entity->product_id->value}"; // TODO: change or verify
$breadcrumb = &$vars['breadcrumb'];
if (!empty($entity->$taxonomy_field_name->entity)) {
$node_url = array_pop($breadcrumb);
$term = $entity->$taxonomy_field_name->entity;
$storage = \Drupal::service('entity_type.manager')
->getStorage('taxonomy_term');
$parents = $storage->loadParents($term->id());
if (!empty($parents)) {
foreach ($parents as $index => $parent) {
array_push($breadcrumb, $parent->toLink());
}
}
array_push($breadcrumb, $term->toLink());
array_push($breadcrumb, $node_url);
// Implementing Cache.
$vars['#cache']['contexts'][] = "url.path";
$vars['#cache']['tags'][] = $cache_tag;
}
}
}
If you also want the parents you can replace
if (!empty($node->field_section->entity)) { $breadcrumb->addLink($node->field_section->entity->toLink()); }
with
if (!empty($node->field_section->entity)) { $term = $node->field_section->entity; $storage = \Drupal::service('entity_type.manager') ->getStorage('taxonomy_term'); $parents = $storage->loadParents($term->id()); if (!empty($parents)) { foreach ($parents as $index => $parent) { $breadcrumb->addLink($parent->toLink()); } } $breadcrumb->addLink($term->toLink()); }
How would can I implement this solution to show the parents but using the YOURTHEME.theme preprocess function instead of the module? Thank you in advance.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you also want the parents you can replace
with