3

I am wondering how to programmatically access metatag module data. For example, my node has an entry for metatag description, and I see in the generated page the meta description tag, which is great. However, it's not clear how I can access this programmatically.

Right now, I am trying the following:

$metatag_manager = \Drupal::service('metatag.manager');
$tags = $metatag_manager->tagsFromEntityWithDefaults($node);
$elements = $metatag_manager->generateRawElements($tags, $node);

Inspecting the data, I see that $tags includes a 'description' entry, but $elements does not. Is there a better way of accessing this data?

The metatag module includes documentation for programmatically setting data, but unfortunately does not mention accessing the data.

Edit: Alas, it seems I was inspecting the wrong node -- one with the same title as a node with metadata entries. Working now with the correct node, it seems all I need to use is:

$metatag_manager = \Drupal::service('metatag.manager');
$tags = $metatag_manager->tagsFromEntity($node);

Which returns an array with a description key and the description value entered for that node.

1 Answer 1

1

If you have node object loaded, you can access the meta tags as below:

$metaTags = $node->get('field_meta_tags')->value;
if (!empty($metaTags)) {
      $metaTagsArr = unserialize($metaTags);
echo "<pre>";
print_r($metaTagsArr);
echo "</pre>";
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.