友情連結是獨立部落格常見需求。雖然外掛能快速實現,但掌握原生 wp_list_bookmarks() 函數與頁面模板技巧,能輕鬆建立免外掛、高效能的友情連結頁。本文詳述建立模板、參數配置、CSS 排版與 jQuery 自動抓取 Favicon 完整流程。
page.php 重命名為 links.php。<?php /* Template Name: Links */ ?>
<div class="post-content"><?php the_content(); ?></div> 替換為:<div class="lists">
<p class="tips">站點隨機排序</p>
<?php wp_list_bookmarks('orderby=rand&show_images=1'); ?>
</div>
links.php 至主題根目錄。| 參數 | 類型 | 說明 | 預設值 |
|---|---|---|---|
| categorize | bool | 是否按分類顯示 | true |
| category | string | 指定分類 ID 顯示 | 所有 |
| category_name | string | 指定分類名稱顯示 | 所有 |
| category_before/after | string | 分類標題前後標籤 | <li id="...">/ </h2> |
| class | string | 分類 ul 的 class | linkcat |
| category_orderby | string | 分類排序欄位 | name |
| category_order | string | 分類升降序 | ASC |
| title_li | string | 連結標題文字 | Bookmarks |
| show_private | bool | 是否顯示私有連結 | false |
| include/exclude | string | 包含/排除分類 ID(逗號分隔) | 無 |
| orderby | string | 連結排序:id, url, name, rating, updated, rand 等 | name |
| order | string | 升降序 | ASC |
| limit | int | 最大輸出條數 | -1 (全部) |
| between | string | 連結/圖片/描述間分隔 | \n |
| show_description | bool | 顯示連結描述 | false |
| show_rating | bool | 顯示等級 | false |
| show_updated | bool | 顯示更新時間 | false |
| hide_invisible | bool | 隱藏不可見連結 | true |
.lists { padding: 5px; margin: 25px auto auto 0; }
.linkcat { font-size: 12px; font-weight: bolder; padding: 5px; margin-bottom: 15px; list-style: none; clear: both; }
.lists li h2 { font-size: 14px; margin-bottom: 15px; color: #99CC33; }
.listcat ul { margin-left: 20px; }
.linkcat ul li {
float: left; margin-bottom: 20px; margin-left: 20px;
padding: 4px 0 4px 6px; width: 150px; border: 1px solid #d9d9d9;
}
.linkcat ul li a { color: #a4a4a4; text-decoration: none; }
.linkcat ul li a img { margin-right: 3px; }
.linkcat ul li a:visited { color: #a4a4a4; }
.tips { font-size: 14px; margin-bottom: 18px; margin-left: 5px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
footer.php 或模板內):$(".linkcat a").each(function(){
var domain = this.href.replace(/^(https?:\/\/[^\/]+).*$/, '$1').replace('https://', '').replace('https://', '');
$(this).prepend('<img src="https://www.google.com/s2/favicons?domain=' + domain + '" style="vertical-align:middle;margin-right:4px;" />');
});
說明:遍歷 .linkcat 下所有連結,解析域名並插入 Google Favicon 服務圖片。若主題結構不同,請調整選擇器(如 .lists a)。
WordPress 3.5+ 預設隱藏連結管理器,需安裝 Link Manager 外掛或在 functions.php 加入:
add_filter('pre_option_link_manager_enabled', '__return_true');
即可在後台「連結」選單新增、編輯、分類管理友情連結。
善用 wp_list_bookmarks() 豐富參數與頁面模板機制,即可零外掛建立功能完整的友情連結頁。搭配 jQuery 自動抓取 Favicon,視覺效果專業且維護輕鬆。參數靈活組合還能實現分類分頁、隨機推薦、限制顯示數量等進階需求。