Twitter Cards with Statamic

Published on Oct 23, 2020


I recently got my blog setup using Statamic and one of the things I noticed immediately was that when I posted a blog post to Twitter, it was very bland. My posts weren't generating the eye-catching card with the image and title of the page. So I quickly sought out how to fix this.

Add the field

For my site, I didn't even have an image tied to the Article collection. That was issue #1 so that'll be the first piece that we fixed. To add a field to the existing collection, you go into the Statamic control panel, click on "Blueprints" then click on "Article". This will bring up a simple interface to add a new field, or link an existing one.

I didn't have any existing asset fields, so I needed to create a new one. I decided to place my hero image in the sidebar so it was easy to see at all times when editing or creating a post. I clicked "Create Field" under "Sidebar" and then chose "Assets". Fill in the "Display" and "Handle" fields appropriately, I used "Hero Image" and "hero_image". The "Handle" is what will be used in the template file to display the field. Click "Finish" and then "Save".

Output the tags

The next step is to make some modifications to the templates. I think it makes sense to use a generic implementation in the global "layout.antlers.html" file. So I added the following couple of lines in the <head> tag.

<meta name='twitter:title' content="{{ title }}" />
<meta name="twitter:description" content="{{ excerpt ?? title }}">
<meta name="twitter:card" content="summary" />

Now, for the Articles, I want things to be a bit more fancy and display the hero image. To do this, I added the following code to the top of the Articles template:

{{ if hero_image }}
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:image" content="{{ hero_image | get:permalink }}" />
{{ /if }}

It's important to use the get:permalink modifier to grab the absolute URL, otherwise Twitter won't know what to do with the relative URL.

You may be thinking, "Don't we have two twitter:card meta tags now? Won't that cause issues?". And the answer is "Yes, there are two and no, it won't cause issues". Luckily, Twitter can handle this just fine and will use the last meta tag. So in this case, it will use the summary_large_image tag and pull in our beautiful hero image along with the title and description.


You'll want to test this to make sure it's working. Luckily, Twitter provides a little tool that will let you do just that. You can find it here.

Wrapping Up

I hope you found this little article helpful. I plan to continue doing this little articles as I work my way through Laravel and Statamic.