Published: October 14, 2017
Adding Tokens for Metatag Image Fields when using Drupal Media Entity
Metatag cannot directly extract an image url from a media field referenced by another entity.
I upgraded my site from Drupal 7 to Drupal 8 this week (yes, that's why it's running on Bartik - a PatternLab developed theme will be installed in time).
This morning I enabled the Metagtag module and set some defaults for page title, description, image, etc. The help notes on the image metatag field says "An image associated with this page, for use as a thumbnail in social networks and other services. This will be able to extract the URL from an image field." This is true, except in my case, all the image fields on the site use the Media Entity module, so they are entity reference fields rather than image fields.
When I put in a token of [node:field_main_image], the result in the outputted metatags was:
<meta property="og:image:url" content="Mark Conroy | DrupalCon Dublin 2017" />
In that case, "Mark Conroy | DrupalCon Dublin 2017" is the name of the referenced media. I needed to output the image field of the referenced media.
After a little trial and error, I came up with this:
[node:field_main_image:entity:field_m_image_image]
which outputs:
<meta property="og:image:secure_url" content="https://mark.ie/sites/default/files/media/images/2017-10/mark_presenting_1.jpg" />
In this case, "field_main_image" is the name of the image field on my content type, and "field_m_image_image" is the name of the image field on my image media bundle.
If you wish to output a specific image style, you can append :default:url
to the token like so:
[node:field_main_image:entity:field_m_image_image:default:url]
or
[node:field_main_image:entity:field_m_image_image:large:url]
To use the image media item's alt tag for your Twitter alt tag, you can do this:
[node:field_main_image:entity:field_m_image_image:alt]
I hope that helps!