I was hitting a roadblock trying to get a sites metatags nice for social sharing, using the Metatags module. In the past I’ve written code to manually generate the meta tags, but thought this time around I would see if I could not reinvent the wheel.

I started to regret my decision when it seemed like tokens for images don’t allow you to serve up derivative images using Image styles. This meant that the only option was to present the image that was uploaded in the raw form - not always what you want. In my case it seemed like some of the source images used by my client were so large that Formerly Twitter ™ was failing to scrape the image because of a timeout or some other limit on their end.

Luckily I came across Jeremiah John’s post:

Drupal 8: How to Get Image Style Tokens for Metatags

Reposting the trick here, because this is a fairly undocumented feature that needs to be propagated and shared. And also to report that this still works in D10.

So, you can get derivatives in image tokens, by putting the name of the Image Style right after the field in the token string, and then url, so for example:



In my particular case, I’m using the Media library, so the token ended up looking a little more convoluted:


And now I’m using this in my Metatags module settings to generate meta tags like:

<meta name="twitter:image" content="https://www.pembina.org/sites/default/files/styles/social_share_card/public/node_images/taxpayers-shouldn-t-foot-the-whole-bill-for-carbon-capture.png?itok=geTIU2Uw">

I’m still not convinced I made the right choice using the Metatags module to handle tag generation as I’ve had to do some other weird stuff to override the defaults when there is a series of image fields that can be used, with fallback. But at least we can get these derivative images.