As a site admin, when I create an event node, I am required to attach an artist node as a reference. The event node page displays the event node date and time with title. The rest of the page is generated by the artist node in full content view mode.

There are no tokens in the metatag feature to reference the 'field_main_image' of the referenced artist node. That is the field we want to become the og:image:url, og:image:width, and og:image:height.

In order to work around this problem, in the theme layer, our developer has added this code:

<?php
function TEMPLATE_page_attachments_alter(array &$attach) {
  if (($node = \Drupal::routeMatch()->getParameter('node')) && $node instanceof \Drupal\node\NodeInterface) {
    // is it an event, artist, or just a plain pages?
    $type = $node->getType();
    if ($type == 'event') {
      if (empty($image = $node->get('field_main_image')->getValue())) {
        $nid = $node->get('field_artist')->getValue();
        $artist = \Drupal\node\Entity\Node::load((int)$nid[0]['target_id']);
        $header_image = $artist->get('field_main_image')->getValue();
        $file = \Drupal\file\Entity\File::load($header_image[0]['target_id']);
        $url = \Drupal\image\Entity\ImageStyle::load('16_9large')
          ->buildUrl($file->getFileUri());
        // Add the og:image
        $attach['#attached']['html_head'][] = array(
          0 => array(
            '#tag' => 'meta',
            '#attributes' => array(
              'name' => 'og:image:url',
              'content' => $url,
            ),
          ),
          1 => 'og_image_url',
        );
        // Add the W and H of the og:image
        $attach['#attached']['html_head'][] = array(
          0 => array(
            '#tag' => 'meta',
            '#attributes' => array(
              'name' => 'og:image:height',
              'content' => '675',
            ),
          ),
          1 => 'og_image_height',
        );
        $attach['#attached']['html_head'][] = array(
          0 => array(
            '#tag' => 'meta',
            '#attributes' => array(
              'name' => 'og:image:width',
              'content' => '1200',
            ),
          ),
          1 => 'og_image_width',
        );
      }
    }
  }
}

How does one build a plugin for Metatag to accomplish what I am doing in the theme layer above?

Thanks!

Joe

Comments

jghyde created an issue. See original summary.

damienmckenna’s picture

Project: Metatag » Token
Component: Open Graph » User interface

It sounds like this is more of a core request or one for the Token module, as Metatag doesn't control what tokens are available.

I'm moving the issue over to the Token module where hopefully someone here will know how to do what you're looking for.

hussainweb’s picture

It sounds this would be fixed by #2493559: Chained tokens for field tokens.

berdir’s picture

Status: Active » Closed (duplicate)

Exactly, closing as duplicate of that.