I want to add variable meta tags depending on the node (a picture and custom title). These custom variables are generated in hook_preprocess_node(). Is there a way to add the metatags inside this function?


yes, you can, place this code in template.php in your subtheme folder

function yourtheme_preprocess_node(&$vars) {
        $element = array(
          '#tag' => 'meta', 
          '#attributes' => array(
            'name' => 'robots', 
            'content' => 'index',
        drupal_add_html_head($element, 'robots');
  • Thanks allot. However I am working with Drupal 8 (sorry forgot to mention that). I found this post: stackoverflow.com/questions/36905114/… but I am not sure if it works in the hook_preproccess_node(). Do you know how it works in 8?
    – Michiel
    Oct 19 '17 at 7:11
  • my code is for D7, not shure if works in D8
    – pinueve
    Oct 19 '17 at 7:13

I am aware that this does not directly answer the question, which was about adding in a preprocess function, but I would suggest that you also consider the metatag module, which is pretty full featured.



For me the following worked: I managed to load the current node in the hook_preprocess_node(). Based on this answer: How do I get the current node ID?

function module_name_page_attachments_alter(array &$page) {

            $node = \Drupal::routeMatch()->getParameter('node');
            if ($node instanceof \Drupal\node\NodeInterface) {
            // You can get nid and anything else you need from the node object.
            $nid = $node->id();

        $ogImage = array(
            '#tag' => 'meta',
            '#attributes' => array(
                'property' => 'og:image',
                'content' => 'location of the image'.$nid.'.png',
    //my picture has the node id before the file format

        $page['#attached']['html_head'][] = [$ogImage, 'ogImage'];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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