How to add Open Graph meta tags in 11ty? #2671
-
|
Hello. I'm having trouble getting my social media images working. I have set up basic Open Graph meta tags on 'base.njk' layout file: <head>
<!-- Open graph -->
<meta property="og:title" content="{{ title }}"/>
<meta property="og:description" content="{{ description }}" />
<meta property="og:image" content="{{ image }}" />
<meta property="og:type" content="article" />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="675" />
<!-- Twitter -->
<meta name="twitter:title" content="{{ title }}">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:site" content="@myusername">
<meta name="twitter:description" content="{{ description}}">
<meta name="twitter:image" content="{{ image }}">
<meta name="twitter:creator" content="@myusername">
</head>I then added them to a frontmatter for all blog posts. This is what my child templates look like: Both the title and description are displaying correctly, but the images are not showing at all when I test them. I've searched around and found only one article and it says the reason why it happened is that the cover image URL must be absolute (e.g. https://mysite.com/src/images/cover-image.png). The solution found in the article involves using an |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
|
I think the cheapest answer is just hardcode the domain prefix in the meta tags. Something like: <head>
<!-- Open graph -->
<meta property="og:image" content="https://mysite.com{{ image }}" />
<!-- Twitter -->
<meta name="twitter:image" content="https://mysite.com{{ image }}">
</head>Sure, would probably be not 100% ideal if you were trying to validate OpenGraph against a local/dev/stage server, but perfectly fine if you're running the production site through a validator. Or, you could write a custom filter which will add your production domain prefix to a URL path, and then use something like eleventyConfig.addFilter("abs_url", function (path, host="https://mysite.com/") {
return new URL(path, host).href;
});USAGE---
title: foo
image: /images/foo.png
---
<meta property="og:image" content="{{ image | abs_url }}" />OUTPUT<meta property="og:image" content="https://mysite.com/images/foo.png" /> |
Beta Was this translation helpful? Give feedback.
-
|
Wow, that worked like a charm! Thank you so much, @pdehaan. I really appreciated it. |
Beta Was this translation helpful? Give feedback.
I think the cheapest answer is just hardcode the domain prefix in the meta tags. Something like:
Sure, would probably be not 100% ideal if you were trying to validate OpenGraph against a local/dev/stage server, but perfectly fine if you're running the production site through a validator.
Or, you could write a custom filter which will add your production domain prefix to a URL path, and then use something like
<meta name="twitter:image" content="{{ image | abs_url }}">. Which might look…