Creating Dynamic Twitter Cards with Cloudinary
Twitter Cards let you attach photos and videos to your tweets so they stand out from the crowd. For Live Chat Labs, where I write Live Chat Reviews as well as articles about Live Chat, I wanted to dynamically generate Twitter Cards based on the content of the article or review I’m linking to. This saves me having to manually create a twitter card each time I want to tweet about a new article or review.
After reading an article on dev.to, I ended up using Cloudinary and am fairly pleased with the results (scroll down past the example for implementation details).
Here’s an example Twitter Card for one of my articles:
Want to add live chat to your WordPress site? Read my article to find out which plugins you can use.https://t.co/FfMgpiARcg
— AhoyLabs (@ahoylabsHQ) September 27, 2019
Implementation
To do this, you’ll need to first sign up for a free Cloudinary account. Once you’ve done that you need to create and a template (or background) image on which your dynamic assets will be displayed. Last time I checked the optimal size for a Twitter Card image was 1024 x 536 pixels. My template image for articles looks like this:
Cloudinary lets you dynamically transform an image including resizing, cropping and adding image or text overlays. Read the API Reference for more details about what you can do.
The next step will depend on how you generate your website. My site is a static site built with Middleman, so I’ve just written a couple of helper methods, which are called when building the site. This helper method is called when building an article. As you can see, I’m just passing in the headline text (“The 10 best live chat plugins…”) and then specifying a font type and size to overlay this headline on to the template image (“livechatlabs_article.png”).