Published: Sat 14 Oct 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.

Metatag Fields set correctly using Media 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]

I hope that helps!

If you like what I write, you might like to follow me on Twitter @markconroy

Permalink

This was a great help, thanks.

For some reason I could not get that last bit with 'default' image style to work, but I did find this worked for me:

[node:field_media_image:entity:field_media_image:entity:url]

where both my referenced field and the image field are called field_media_image.

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.