部落格前一個佈景主題是 Initial,用了兩三年,後來換成 Facile,目前是 2.5 版。為了日後方便跟著作者更新,只按自己的需求做了些調整。
1、自訂 CSS 樣式
header .navbar{border-width:0 0 1px 0;}
.post-list .post .post-title{font-size:26px;}
.sidebar section h2{font-size:14px;}
.sidebar section ul li{font-size:14px;}
.sidebar section ul li a{font-size:14px;}
.sidebar .latest-comment .media-body p{font-size:14px;}
.text-color{font-size:14px;word-wrap:break-word;word-break:break-all;}
.post-page article .post-content p{line-height:1.8;}
.post-page article .post-content img:not(.logo){display:inline;}
.post-page article .post-content blockquote{font-size:14px;padding:10px 10px 10px 20px;border-radius:0.5rem;}
.light-color .post-page article .post-content blockquote{border-left:4px solid #ca896d;background:#f3f3f3;color:#444;}
.dark-color .post-page article .post-content blockquote{border-left:4px solid #d69d85;background:#1e1e1e;color:#bbb;}
.archive-title{border-radius:4px;padding:18px 20px 10px;text-align:center;}
.archive-page .archives .archives-item ul li .day{text-align:right;}
.light-color .archive-title{background:#f3f3f3;}
.dark-color .archive-title{background:#16161a;}
.nav-item{font-size:14px;}
.nitxt .form-control{height:calc(2.25em + .75rem + 3px);}
.nitxt .required{color:#f00;}
.text-truncate{font-size:16px;}
.table-responsive{font-size:16px;}
code{font-size:100%;padding:0 4px;}
#comments .comment-input .row div{margin-bottom:0;}
#comments .comment-input .row div.nitxt{margin-bottom:16px;}
#comments .comments-lists .comment-author .comment-reply a, #comments .comments-lists .comment-author .comment-reply i{font-size:12px;color:#888;}
#copyright-info p{font-size:.8125rem;line-height:120%;}
#copyright-info p a{font-size:.8125rem;}
footer .text-center {font-size:12px;}
@media screen and (max-width:575px) {
.post-list .post .post-title{font-size:22px;}
.post-page .post-title{font-size:24px;}
}
@media (prefers-color-scheme: dark) {
.archive-title{background:#16161a;}
.post-page article .post-content blockquote{border-left:4px solid #d69d85;background:#1e1e1e;color:#bbb;}
}
@media (prefers-color-scheme: light) {
.archive-title{background:#f3f3f3;}
.post-page article .post-content blockquote{border-left:4px solid #ca896d;background:#f3f3f3;color:#444;}
}註:在 comment-input.php 中,把input和textarea上層div的class加上nitxt,讓輸入框和驗證碼 Captcha 的高度一致。
2、自訂 JS,讓內容中的站內連結自動取消 target="_blank"
<script>
document.addEventListener('DOMContentLoaded',function(){
const h=window.location.hostname,l=document.querySelectorAll('.post-content a');
l.forEach(i=>{const r=i.getAttribute('href');r&&(!r.startsWith('http')||r.includes(h))&&(i.target='_self',i.removeAttribute('target'))});
});
</script>註:作者範本的全域 JS 已經加上了 target="_blank"。
3、標題和範本副標題之間加上「-」分隔
找到 header.php 裡的 <?php if ($this->is('index')) echo $this->options->tagline; ?>,改成:<?php if ($this->is('index')) echo ' - ' . $this->options->tagline; ?>
4、導覽選單加上文章分類
找到 header.php 裡的 <?php $this->widget('Widget_Contents_Page_List')->to($pages); ?>,在它上面加入:
<?php $this->widget('Widget_Metas_Category_List@nav')->to($category); ?>
<?php while($category->next()): ?>
<li class="nav-item<?php if ($this->is('category', $category->slug)) echo ' active'; ?>">
<a class="nav-link" href="<?php $category->permalink(); ?>"<?php if ($this->is('category', $category->slug)) echo ' aria-current="category"'; ?>><?php $category->name(); ?></a>
</li>
<?php endwhile; ?>5、分享內容頁給好友或朋友圈時,顯示縮圖和簡介
找到 header.php 裡的 <link rel="icon" href="<?php echo $this->options->logoUrl?$this->options->logoUrl:$this->options->siteUrl . 'favicon.ico'; ?>" type="image/x-icon">,在它上面加入:
<?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.png';
}
// 獲取描述
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="800" />
<meta property="og:image:height" content="800" />
<meta property="og:description" content="<?php echo htmlspecialchars($description) ?>" />
<meta property="og:site_name" content="<?php $this->options->title() ?>" />
<!-- Twitter -->
<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 ?>" />
<!-- Wechat -->
<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; ?>6、遮蔽 <head> 區塊相關的 meta 輸出
找到 header.php 裡的 <?php $this->header(); ?>,改成:<?php $this->header('generator=&template=&pingback=&xmlrpc=&wlw=&rss1=&rss2=&atom=&social='); ?>
註:social 是 Typecho 1.3.0 新增的。7、右側 sidebar 新增隨機文章
在 helpers.php 最下方新增:
function getRandomPosts($random = 5) {
$db = Typecho_Db::get();
$adapterName = $db->getAdapterName(); // 相容非MySQL資料庫
if ($adapterName == 'pgsql' || $adapterName == 'Pdo_Pgsql' || $adapterName == 'Pdo_SQLite' || $adapterName == 'SQLite') {
$order_by = 'RANDOM()';
} else {
$order_by = 'RAND()';
}
$sql = $db->select()->from('table.contents')
->where('status = ?', 'publish')
->where('table.contents.created <= ?', time())
->where('type = ?', 'post')
->limit($random)
->order($order_by);
$result = $db->fetchAll($sql);
if ($result) {
foreach ($result as $val) {
// 例項化內容元件並推入資料行
$obj = Typecho_Widget::widget('Widget_Abstract_Contents');
$obj->push($val);
// 透過物件屬性獲取資料,避免陣列鍵缺失
$post_title = htmlspecialchars($obj->title);
$permalink = $obj->permalink;
echo '
<li>
<a href="' . $permalink . '" title="' . $post_title . '">' . $post_title . '</a>
</li>';
}
}
}sidebar.php 對應的位置新增:
<?php if ($component == '推薦閱讀'): ?>
<!--最新文章-->
<section class="ml-xl-4 ml-lg-3 mb-5">
<h2 class="mb-4"><?php echo $GLOBALS['t']['sidebar']['recommendPosts']; ?></h2>
<ul aria-label="<?php echo $GLOBALS['t']['sidebar']['recommendPosts']; ?>">
<?php getRandomPosts(10);?>
</ul>
</section>
<?php endif; ?>在語言包中 'sidebar' => array( 下面新增:'recommendPosts' => '推薦閱讀',,英文語言包也要一併加上。最後到「外觀 → 設定外觀」的「側邊欄元件」處加上 推薦閱讀。
8、讓文章內容中的非本站連結加上 rel="nofollow"
找到 post.php 裡的這段程式碼:
$GLOBALS['post']['content'] = addBootstrapTableClasses($GLOBALS['post']['content']);在它下面新增:
// ========== 核心功能:外鏈自動新增 rel="nofollow"(適配泛域名) ==========
function autoAddNofollowToExternalLinks($content, $siteUrl) {
// 1. 解析並標準化本站根域名(提取 yourname.site,相容所有二級域名)
$siteParsed = parse_url(rtrim($siteUrl, '/'));
$siteHost = isset($siteParsed['host']) ? strtolower($siteParsed['host']) : '';
if (empty($siteHost)) return $content;
// 提取根域名
$siteHostParts = explode('.', $siteHost);
$rootDomain = count($siteHostParts) >= 2
? $siteHostParts[count($siteHostParts)-2] . '.' . $siteHostParts[count($siteHostParts)-1]
: $siteHost; // 兜底:防止域名格式異常
// 2. 正則匹配所有<a>標籤,捕獲href和所有屬性
$pattern = '/<a\s+([^>]*?)href=["\']([^"\']+)["\']([^>]*?)>/i';
$content = preg_replace_callback($pattern, function($matches) use ($rootDomain) {
$fullTag = $matches[0];
$preHrefAttr = trim($matches[1]); // href前的屬性
$href = $matches[2]; // 連結地址
$postHrefAttr = trim($matches[3]); // href後的屬性
$allAttrs = $preHrefAttr . ' ' . $postHrefAttr; // 拼接所有屬性(去重空格)
$allAttrs = preg_replace('/\s+/', ' ', $allAttrs);
// 3. 判斷是否為站內連結(核心:泛域名匹配 *.yourname.site)
$isInternal = false;
$hrefTrim = rtrim($href, '/');
// 情況1:相對路徑(無域名,如 /post/123、about.html)
if (strpos($href, '://') === false && !preg_match('/^\/\/[^\/]+/', $href)) {
$isInternal = true;
}
// 情況2:絕對路徑(含 *.yourname.site 域名)
else {
$hrefParsed = parse_url($hrefTrim);
$hrefHost = isset($hrefParsed['host']) ? strtolower($hrefParsed['host']) : '';
if (!empty($hrefHost)) {
// 匹配規則:
// 1. 精準匹配根域名(yourname.site)
// 2. 匹配所有二級域名(*.yourname.site)
if ($hrefHost === $rootDomain || substr($hrefHost, -strlen($rootDomain) - 1) === '.' . $rootDomain) {
$isInternal = true;
}
}
}
// 4. 站內連結直接返回原標籤,不做任何修改
if ($isInternal) {
return $fullTag;
}
// 5. 外鏈:檢查是否已有rel="nofollow"(避免重複新增)
if (preg_match('/rel\s*=\s*["\'](.*?)nofollow(.*?)["\']/i', $allAttrs)) {
return $fullTag;
}
// 6. 外鏈且無nofollow:新增/追加rel="nofollow"
if (preg_match('/rel\s*=\s*["\'][^"\']+["\']/i', $allAttrs)) {
// 已有rel屬性,追加nofollow(如 rel="noopener" → rel="noopener nofollow")
$allAttrs = preg_replace('/rel\s*=\s*["\']([^"\']+)["\']/i', 'rel="$1 nofollow"', $allAttrs);
} else {
// 無rel屬性,新增rel="nofollow"
$allAttrs .= ' rel="nofollow"';
}
// 7. 重新拼接<a>標籤(保持屬性順序,僅修改rel)
return '<a ' . trim($allAttrs) . ' href="' . $href . '">';
}, $content);
return $content;
}
// 執行外鏈處理(傳入本站域名)
$GLOBALS['post']['content'] = autoAddNofollowToExternalLinks(
$GLOBALS['post']['content'],
$this->options->siteUrl
);
// ========== 外鏈處理結束 ==========
評論 暫無評論