在 Typecho 博客中实现文章链接在 Telegram 中的预览,需要生成符合 Telegram 链接预览要求的元数据,通常通过 Open Graph(OG)协议标签完成。以下是具体步骤:

1. 启用 Open Graph 元数据

在 Typecho 博客的主题中,添加 Open Graph 元数据到 <head> 部分。编辑你的主题文件(通常是 header.phpindex.php),在 <head> 标签内加入以下代码:

<meta property="og:type" content="article" />
<meta property="og:title" content="<?php $this->title(); ?>" />
<meta property="og:description" content="<?php $this->excerpt(100, '...'); ?>" />
<meta property="og:url" content="<?php $this->permalink(); ?>" />
<meta property="og:image" content="你的默认图片URL或者动态生成的文章缩略图URL" />

解释:

  • og:type:内容类型,文章类型一般用 article
  • og:title:文章标题。
  • og:description:文章摘要,可调用 Typecho 的 $this->excerpt()
  • og:url:文章的完整链接。
  • og:image:分享时的缩略图,建议每篇文章设置一张图片。如果没有,可以设置默认图片。

2. 确保主题图片支持动态生成

如果每篇文章有特定图片,可以这样设置:

<?php if ($this->fields->thumbnail): ?>
<meta property="og:image" content="<?php echo $this->fields->thumbnail; ?>" />
<?php else: ?>
<meta property="og:image" content="默认图片URL" />
<?php endif; ?>

3. 在主题启用 HTTPS

Telegram 的链接预览要求链接必须是 HTTPS。如果你的站点没有 HTTPS,建议安装 SSL 证书(例如通过 Let's Encrypt 免费获取)。

4. 测试链接预览

使用 Telegram 的 @WebPageBot 测试链接预览效果。发送文章链接,如果成功,会显示你设置的标题、描述和图片。

5. 调试工具

如果预览不成功,可以使用以下工具检查你的页面是否正确生成了 Open Graph 标签:

最终完整代码

以下是最终的完整代码,你可以将其添加到主题的 <head> 部分(通常是 header.php 或者 index.php 文件)。这个代码会根据文章是否设置了图片来输出相应的 Open Graph og:image

    <!-- Open Graph Meta Tags -->
    <meta property="og:type" content="article" />
    <meta property="og:title" content="<?php $this->title(); ?>" />
    <meta property="og:description" content="<?php $this->excerpt(100, '...'); ?>" />
    <meta property="og:url" content="<?php $this->permalink(); ?>" />
    
    <?php 
    // 判断是否有文章图片
    if ($this->fields->thumbnail): 
    ?>
        <meta property="og:image" content="<?php echo $this->fields->thumbnail; ?>" />
    <?php else: ?>
        <meta property="og:image" content="https://你的站点.com/path/to/logo.jpg" />
    <?php endif; ?>

说明:

  1. $this->fields->thumbnail

    • 如果你的文章字段支持 thumbnail 自定义字段,可以用这个来判断。
    • 如果没有,请确保在文章自定义字段里添加一个名为 thumbnail 的图片 URL。
  2. 默认图片路径
    替换 https://你的站点.com/path/to/logo.jpg 为你网站 LOGO 图片的完整 URL。
  3. 文章摘要长度
    <?php $this->excerpt(100, '...'); ?> 可以生成 100 字的文章摘要,你可以根据需求调整长度。

调试和测试

  • 确保文章有图片的字段正确设置:在后台检查文章是否有 thumbnail 字段,并确保字段内容为有效的图片 URL。
  • 预览验证:使用 Telegram 的 @WebPageBotMeta Tag Debugger 来测试链接预览效果。

这样,无论文章是否有图片,Telegram 都会显示适当的预览效果。