metatag.api.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. /**
  3. * @file
  4. * Document all supported APIs.
  5. */
  6. /**
  7. * Provides a ability to integrate alternative routes with metatags.
  8. *
  9. * Return an entity when the given route/route parameters matches a certain
  10. * entity. All meta tags will be rendered on that page.
  11. *
  12. * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
  13. * The route match.
  14. *
  15. * @return \Drupal\Core\Entity\EntityInterface|null
  16. * Return an entity, if the route should use metatags.
  17. */
  18. function hook_metatag_route_entity(\Drupal\Core\Routing\RouteMatchInterface $route_match) {
  19. if ($route_match->getRouteName() === 'example.test_route') {
  20. if ($node = $route_match->getParameter('node')) {
  21. return $node;
  22. }
  23. }
  24. }
  25. /**
  26. * Alter the meta tags for pages that are not of content entities.
  27. *
  28. * @param array $metatags
  29. * The special meta tags to be added to the page.
  30. * @param array $context
  31. * The context for the current meta tags being generated. Will contain the
  32. * following:
  33. * 'entity' - The entity being processed; passed by reference.
  34. */
  35. function hook_metatags_alter(array &$metatags, array &$context) {
  36. // Exclude meta tags on frontpage.
  37. if (\Drupal::service('path.matcher')->isFrontPage()) {
  38. $metatags = NULL;
  39. }
  40. }
  41. /**
  42. * Alter the meta tags for any page prior to page attachment.
  43. *
  44. * @param array $metatag_attachments
  45. * An array of metatag objects to be attached to the current page.
  46. */
  47. function hook_metatags_attachments_alter(array &$metatag_attachments) {
  48. if (\Drupal::service('path.matcher')->isFrontPage() && \Drupal::currentUser()->isAnonymous()) {
  49. foreach ($metatag_attachments['#attached']['html_head'] as $id => $attachment) {
  50. if ($attachment[1] == 'title') {
  51. $metatag_attachments['#attached']['html_head'][$id][0]['#attributes']['content'] = 'Front Page Title for Anonymous Users';
  52. }
  53. }
  54. }
  55. }