The Metatags Contributed Module in Drupal provides users with the ability to insert various meta tags into their web pages. However, in certain situations, it may be necessary to alter metatags to improve website performance. To accomplish this, three hooks can be utilized to modify or change incoming metatags.
1. hook_metatags_alter:
Modify/Alter the meta tags for both content and non-content entities.
/**
* Implements hook_metatags_alter().
*/
function drupaljournal_base_metatags_alter(array &$metatags, array &$context) {
$node = \Drupal::routeMatch()->getParameter('node');
$is_admin = \Drupal::service('router.admin_context')->isAdminRoute();
if (
!$is_admin &&
$node instanceof NodeInterface &&
$node->hasField('field_enable_schema_metatag') &&
$node->get('field_enable_schema_metatag')->value != 1) {
// Remove schema article metatags.
$metatags = array_filter($metatags, function($k) {
return !str_starts_with($k, "schema_article_");
}, ARRAY_FILTER_USE_KEY);
}
}
2. hook_metatags_attachments_alter:
Alter the meta tags for any page prior to the page attachment.
/**
* Implements hook_metatags_attachments_alter().
*/
function drupaljournal_base_metatags_attachments_alter(array &$metatag_attachments) {
if (\Drupal::service('path.matcher')->isFrontPage() && \Drupal::currentUser()->isAnonymous()) {
foreach ($metatag_attachments['#attached']['html_head'] as $id => $attachment) {
if ($attachment[1] == 'title') {
$metatag_attachments['#attached']['html_head'][$id][0]['#attributes']['content'] = 'Front Page Title for Anonymous Users';
}
}
}
}
3. hook_page_attachments_alter:
/**
* Implements hook_page_attachments_alter().
*/
function drupaljournal_base_page_attachments_alter(array &$page) {
$viewport = [
'#type' => 'html_tag',
'#tag' => 'meta',
'#attributes' => [
'name' => 'viewport',
'content' => 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no',
],
];
$page['#attached']['html_head'][] = [$viewport, 'viewport'];
}