0

Do youknow how to add the image url to the head tag?

This is what I've tried so far

Example

<head>
     <meta property="og:image" content="  {{ file_create_url(node.field_image.0.entity.uri.value) }}        "/>
     <meta property="og:image:secure_url" content="  {{  file_create_url(node.field_image.0.entity.uri.value)  }} " />
</head>

Thanks!

1

Or possibly a better solution - use the metatag module and you can customise this through the CMS globally or for specific pages. "og" stands for Open Graph so you just need to pop your data in the relevant open graph section

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

|improve this answer|||||
0

Probably the best place to do this is in a node preprocess function and then attach it for the render array. How it could be:

/**
 * Implements hook_preprocess_node().
 */
function themename_preprocess_node(&$variables) {
  // Load the image field values from the node.
  $image_field = $variables['node']->get('field_image')->getValue();
  // Get the first item of the field values.
  $image_field = reset($image_field);
  // Load file by the file id.
  $image = file_load($image_field['target_id']);

  // Create the actual HTML by creating a render array.
  $og_image = [
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => [
      'property' => 'og:image',
      'content' => $image->toUrl(),
    ],
  ];

  $variables['#attached']['html_head'][] = [$og_image, 'og:image'];
}
|improve this answer|||||
  • I need it for drupal 8, do you know what it would be for drupal 8 please? – user3350619 Dec 9 '15 at 19:27
  • 1
    That is for Drupal 8 – lauriii Dec 10 '15 at 20:24

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.