Typecho博客在分享内容页给好友或朋友圈时,显示缩微图和简介的模板代码
在分享日志内容给好友或者朋友圈的时候,需要显示缩微图和简介内容。
使用Open Graph协议,修改主题文件(header.php),在<head>标签内添加以下代码(带自定义字段支持):
<?php if ($this->is('post') || $this->is('page')): ?>
<?php
// 获取缩略图
$thumb = '';
// 先尝试自定义字段
if ($this->fields->thumb) {
$thumb = $this->fields->thumb;
}
// 再尝试自动获取第一张图片
else {
preg_match('/<img[^>]+src=[\'"]([^\'"]+)[\'"][^>]*>/i', $this->content, $matches);
if (!empty($matches[1])) {
$thumb = $matches[1];
}
}
// 处理图片路径,确保是完整URL
if (!empty($thumb)) {
// 如果已经是完整URL(http/https或//开头),不做处理
if (!preg_match('/^(https?:)?\/\//i', $thumb)) {
// 不是完整URL,需要加上网站根URL
if (strpos($thumb, '/') === 0) {
// 以斜杠开头,是网站根目录下的绝对路径
$thumb = rtrim($this->options->siteUrl, '/') . $thumb;
} else {
// 相对路径,使用网站根URL作为基础
$thumb = rtrim($this->options->siteUrl, '/') . '/' . ltrim($thumb, '/');
}
}
}
// 没有图片,使用默认
else {
$thumb = rtrim($this->options->siteUrl, '/') . '/usr/themes/' . $this->options->theme . '/images/default-og.jpg';
}
// 获取描述
if ($this->fields->excerpt) {
$description = $this->fields->excerpt;
} elseif ($this->description) {
$description = $this->description;
} else {
$description = Typecho_Common::subStr(strip_tags($this->excerpt), 0, 150, '...');
}
?>
<meta property="og:title" content="<?php $this->title() ?>" />
<meta property="og:type" content="article" />
<meta property="og:url" content="<?php $this->permalink() ?>" />
<meta property="og:image" content="<?php echo $thumb ?>" />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
<meta property="og:description" content="<?php echo htmlspecialchars($description) ?>" />
<meta property="og:site_name" content="<?php $this->options->title() ?>" />
<!-- Twitter Card -->
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="<?php $this->title() ?>" />
<meta name="twitter:description" content="<?php echo htmlspecialchars($description) ?>" />
<meta name="twitter:image" content="<?php echo $thumb ?>" />
<!-- 微信特殊标签 -->
<meta property="wechat:article:title" content="<?php $this->title() ?>" />
<meta property="wechat:article:description" content="<?php echo htmlspecialchars(Typecho_Common::subStr(strip_tags($description), 0, 120, '...')) ?>" />
<meta property="wechat:article:image" content="<?php echo $thumb ?>" />
<?php endif; ?>这样设置后,你的Typecho博客在微信、QQ、微博等平台分享时就会显示美观的缩略图和简介了!
优化获取图片地址备注:
1、使用正则表达式判断是否是完整URL(以http://、https://或//开头)
2、如果不是完整URL,再判断是绝对路径(以/开头)还是相对路径
3、绝对路径直接拼接网站根URL
4、相对路径根据实际情况处理(简单版本可以统一加上网站根URL)
这样处理后,无论图片路径是哪种形式,最终都能得到完整的URL,确保在微信、QQ等平台分享时能正常显示缩略图。
当然,还有其他方法(如插件)可实现。
Copyright Notice: This article is an original work. Copyright belongs to A君网志. Please contact the author for permission before reprinting.
Article URL: https://nipang.cn/share-typecho.html
If you have any questions or concerns about this article, feel free to leave a comment. I will try my best to respond as soon as possible.