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 等平台分享時能正常顯示縮圖。

當然,還有其他方法(例如外掛)可以實現。

發表評論

評論 暫無評論

文章目錄