Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add meta tag to head in drupal 8

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?

like image 273
Aashi Avatar asked Mar 10 '16 10:03

Aashi


2 Answers

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

like image 156
Danielishko Avatar answered Oct 28 '22 23:10

Danielishko


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 !

like image 24
Antoine Subit Avatar answered Oct 29 '22 00:10

Antoine Subit