Get meta tags programmatically

Components

To access the meta tags field data created by the Metatag module you can use the Metatag Manager service.

$metatag_manager = \Drupal::service('metatag.manager');

First, get the tags from the entity (usually from a node):

$tags = $metatag_manager->tagsFromEntityWithDefaults($node);

and then generate the meta tag values:

$metatags = $metatag_manager->generateTokenValues($tags, $node);

In summary, the Metatag Manager service in Drupal allows for programmatic retrieval of meta tags associated with an entity.

About the Author

Goran Nikolovski is a web and AI developer with over 10 years of expertise in PHP, Drupal, Python, JavaScript, React, and React Native. He founded this website and enjoys sharing his knowledge.