-1

How to add variable meta tags depending on the node that is loaded?

The node has a picture and custom title field and the need to be variable. What is the best practice to change them in: hook_preprocess_node()?

3 Answers 3

2

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.

https://www.drupal.org/project/metatag

1

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');
 } 
2
  • 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, 2017 at 7:11
  • my code is for D7, not shure if works in D8
    – pinueve
    Oct 19, 2017 at 7:13
0

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 and acknowledge that you have read and understand our privacy policy and code of conduct.

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