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 senior web developer who loves working with Drupal, React, and React Native. He is the founder of this website and he enjoys sharing his knowledge. Need help with anything? Get in touch.