How to add an Open Graph image tag to a blog post in Gatsby’s blog starter

Gatsby’s blog starter is great, but I’ve run into a problem: I’m trying to share my blog posts on social media, but LinkedIn isn’t showing the featured image for each blog post.

LinkedIn’s Post Inspector says that we need to provide a metadata tag for the og:image in the blog post’s head section. For example:

<meta name="image" property="og:image" content="[Image URL here]">

Key point: My Gatsby blog sources data from WordPress.

Julian Garamendy’s blog post Adding custom OpenGraph images to Gatsby Starter Blog helped me to understand what files to edit. But his example seems to be using Markdown Pages as the data source instead of WordPress.

Step 1 – Edit seo.js

First I had to edit src/components/seo.js to support the output of an Open Graph image tag. View these changes on GitHub.

Step 2 – Edit blog-post.js

Then I edited src/components/blog-post.js to do two things:

  1. Query WordPress for the source URL of the featured image
  2. Invoke the SEO module to output the featured image URL in an og:image meta tag

View these changes on GitHub.

Conclusion and Next Steps

This was a relatively easy way to make my blog posts display a featured image when shared on LinkedIn. The only possible drawback to the solution described in this blog post is that it uses the sourceURL of the featured image rather than URL of the image after the site is compiled by Gatsby.

Featured image photo by Laura Fuhrman on Unsplash

Leave a Reply

Your email address will not be published. Required fields are marked *