I want to add meta tags to my site.
I added this code in my THEME.theme file and cleared the cache.
/**
* Implements hook_page_attachments_alter().
*
* Include meta tags and fonts using attachment method.
*/
function bartik_page_attachments_alter(array &$page) {
$font_attributes = array(
'rel' => 'stylesheet',
'type' => 'text/css',
'href' => 'https://fonts.googleapis.com/css?family=Lato:400,100,100italic,300,300italic,400italic,700',
);
$page['#attached']['html_head_link'][] = array($font_attributes);
$rendering_meta = array(
'#type' => 'html_tag',
'#tag' => 'meta',
'#attributes' => array(
'name' => 'SKYPE_TOOLBAR',
'content' => 'SKYPE_TOOLBAR_PARSER_COMPATIBLE',
),
);
$page['#attached']['html_head'][] = [$rendering_meta, 'rendering_meta'];
}
This code just attaches the meta tag to the login page.
What should I do to add the meta tag to all the site pages?
What I did to add meta tag to head was:
function theme_preprocess_html(&$variables) {
$xuacompatible = [
'#tag' => 'meta',
'#attributes' => [
'http-equiv' => 'x-ua-compatible',
'content' => 'ie=edge',
],
];
$variables['page']['#attached']['html_head'][] = [$xuacompatible, 'x-ua-compatible'];
};
It results in
<meta http-equiv="x-ua-compatible" content="ie=edge">
Maybe not the best solution but it works :)
Good luck
This following code is working for me to override meta title and description with custom fields from Basic Page content type :
/**
* Implements hook_preprocess_html() for html templates.
*/
function theme_preprocess_html(&$variables)
{
// Add META tag title + description from back-office node basic page field
$node = \Drupal::routeMatch()->getParameter('node');// Load the node entity from current route
if ($node) {
if ($node->getType() === 'page') {// Check if node type is basic page
$title = [
'#tag' => 'meta',
'#attributes' => [
'name' => 'title',
'content' => $node->get('field_custom_meta_title')->value,
],
];
$description = [
'#tag' => 'meta',
'#attributes' => [
'name' => 'description',
'content' => $node->get('field_custom_meta_description')->value,
],
];
$variables['page']['#attached']['html_head'][] = [$title, 'title'];
$variables['page']['#attached']['html_head'][] = [$description, 'description'];
}
}
}
Happy coding !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With