I need to display an image url in a metatag item. The problem is on one of my node types, the editors only upload an image as a media entity inside the body.
What is the best way to handle this?
I feel like there is a better way but I just quickly created a custom token.
<?php
/**
* @file
* Node custom functionality.
*/
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\image\Entity\ImageStyle;
/**
* Implements hook_token_info().
*/
function my_custom_module_token_info() {
$type = [
'name' => t('My Custom'),
'description' => t('My Custom Tokens.'),
'needs-data' => 'node',
];
$node['body_first_media_image_url'] = [
'name' => t("Body First Media Image Url"),
'description' => t("Body's first media image url."),
];
return [
'types' => ['node' => $type],
'tokens' => ['node' => $node],
];
}
/**
* Implements hook_tokens().
*/
function my_custom_module_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
$replacements = [];
if ($type == 'node' && !empty($data['node'])) {
/** @var \Drupal\node\NodeInterface $node */
$node = $data['node'];
foreach ($tokens as $name => $original) {
switch ($name) {
// The first media item embedded in body.
case 'body_first_media_image_url':
$dom = new DOMDocument();
@$dom->loadHTML($node->body->value);
$embedEntities = $dom->getElementsByTagName('drupal-entity');
if ($embedEntities->length > 0) {
$uuid = $embedEntities->item(0)->getAttribute('data-entity-uuid');
$media = \Drupal::entityManager()->loadEntityByUuid('media', $uuid);
$url = ImageStyle::load('extra_large')->buildUrl($media->image[0]->entity->uri->value);
$replacements[$original] = $url;
}
break;
}
}
}
return $replacements;
}