如何使用帖子封面图像作为twitter的卡片图像



我试图使用GridsomemetaInfo创建一张Twitter卡片,其中包含当前帖子的封面图像,但该图像未显示在卡片中。

<template>
<Layout>
...
<g-image ref="coverImage" alt="Cover image" v-if="$page.post.cover_image" :src="$page.post.cover_image" />
...
</Layout>
</template>
<script>
export default {
metaInfo () {
return {
title: this.$page.post.title,
meta: [{
property: 'og:image',
content: this.$refs.coverImage? this.$refs.coverImage.src : (this.$page.meta.siteUrl + '/logo/LOGO.png')
}]
}
}
}
</script>
<page-query>
query Post ($id: ID!) {
post: post (id: $id) {
title
path
cover_image (width: 860, blur: 10)
},
meta: metadata {
siteUrl
},
}
</page-query>

由于g-image知道如何解析图像路径,我必须使用它来将图像路径放在meta标签中。


编辑这个问题是为了记录我的知识,我知道答案,我希望这个问题本身就很好

要使Twitter Card工作,您需要几个步骤。

获取真实图像路径

你是对的,当你查询GraphQL的图像,你得到一个对象,而不是图像路径。但是要获取图像路径,您只需要访问对象中的src属性:

metaInfo () {
return {
title: this.$page.post.title,
meta: [{
property: 'og:image',
content: this.$page.post.cover_image?.src || '/logo/LOGO.png'
}]
}
}

获取正确的图像大小

此卡的图像支持2:1的宽高比最小尺寸为300x157或最大尺寸为4096x4096像素
Twitter Docs(搜索twitter:image)

在网上,你可以找到推荐的尺寸是1200x630,参见Open Graph Docs。

当然,最好确保您使用的图像具有正确的尺寸,但即使您的图像不是脚,您也可以通过GraphQL查询具有正确尺寸的图像,并且它会在需要时裁剪您的图像:

<page-query>
query Post ($id: ID!) {
post: post (id: $id) {
...
cover_image (width: 1200, height: 630)
},
}
</page-query>

完整图像路径

Twitter需要完整路径到您的图像(Facebook,例如,接受相对于主机的路径),因此您需要将siteUrl连接到图像路径:

meta: [{
name: 'twitter:image',
content: this.$page.meta.siteUrl + (this.$page.post.cover_image?.src || '/logo/LOGO.png')
}]

杂项和测试

当然,您需要定义其他meta标签,请注意,Twitter标签应该与namecontent,但Open Graph标签应该与propertycontent:
<!-- For Open Graph -->
<meta property="og:image" content="path/to/image.png">
<!-- For Twitter -->
<meta name="twitter:image" content="path/to/image.png">

然后,使用这些工具验证您的页面,并查看它们的警告:

  • 推特卡验证器
  • Facebook Sharing Debugger
  • LinkedIn Post Inspector

另外,您可以使用Localhost Open Graph Checker扩展来测试您的本地网站。

最新更新