The Metatag is a popular module that provides structured meta-information about a website and even a webpage. It's fairly simple to use and setup. Check out Configuring the Drupal 8 Metatag Module by one of my colleagues for more information.

Services provided by Metatag

The Metatag module has a dependency on the Token module, which it uses to replace the tokens with actual values on render. So, there will be no field data for an entity unless the metatag fields are overwritten with custom values and not using the token replacements.

Metatag defines a metag.manager service in the metatag.services.yml which provides certain methods to get the field values. However, it depends on how the entity is saved with the meta field values. As mentioned before, either using the replacement token defined the metatag configuration or overwrite the field values on an entity.

Fetch the overwritten meta values

For an entity that has overwritten the meta fields the values are stored in the database in a serialized format. To extract, all tags of a given entity use the tagsFromEntity method which will return an array of the values.


$entity = $this->entityTypeManager->getStorage('node')->load($nid);
return $this->metatagManager->tagsFromEntity($entity);

Fetch meta values using token replacements

However, for an entity which uses token replacement to render the meta field values, we need to use another service from the metatag.services.yml that is the metatag.token service. The service provides a replace method which inturns call the Drupal\Core\Utility::replace method to replace the token with appropriate values.


// Load a node
$entity = $this->entityTypeManager->getStorage('node')->load(70);
if (!$entity instanceof EntityInterface) {
  throw new \UnexpectedValueException("Not an entity");
}

// Extracts all tags of a given entity.
// And combines them with sitewide, per-entity-type, and per-bundle defaults.
$tags = $this->metatagManager->tagsFromEntityWithDefaults($entity);

// Iterate through the $tags and pass it to Drupal\metatag::replace
foreach ($tags as $key => $value) {
  $metatags[$key] = $this->metatagToken->replace($value, ['node' => $entity]);
}