function yoast_seo_metatags_alter in Real-time SEO for Drupal 8.2
Implements hook_metatags_alter().
If an entity has values for the custom title or description fields then we use those values in place of the metatags defaults.
File
- ./
yoast_seo.module, line 103 - Contains yoast_seo.module.
Code
function yoast_seo_metatags_alter(array &$metatags, array $context) {
// Without entity there is nothing for us to do.
if (empty($context['entity'])) {
return;
}
/** @var \Drupal\Core\Entity\FieldableEntityInterface $entity */
$entity = $context['entity'];
// Make sure we have a fieldable entity or our SeoManager will produce errors.
if (!$entity instanceof \Drupal\Core\Entity\FieldableEntityInterface) {
return;
}
/** @var \Drupal\yoast_seo\SeoManager $seo_manager */
$seo_manager = \Drupal::service('yoast_seo.manager');
$seo_field = $seo_manager
->getSeoField($entity);
// Abort early if we're not enabled for this entity type.
if (is_null($seo_field)) {
return;
}
$field_item = $seo_field
->first();
// If the field has no value then we're done as well.
if (empty($field_item)) {
return;
}
$values = $field_item
->getValue();
// If we have a custom title, use it instead of the default one.
if (!empty($values['title'])) {
$metatags['title'] = $values['title'];
}
// If we have a custom description, use it instead of the default one.
if (!empty($values['description'])) {
$metatags['description'] = $values['description'];
}
}