WordPress 內置的標簽云工具,放在側邊欄太浪費空間資源,嚴重影響部落格的運行速度,不如親手建立一個彩虹標籤雲頁面,方便閱讀者查找,也方便寫作文章時,選擇適合的 Tags 名稱,對於搜尋引擎有友好的收錄。
1. 首先在 WP 的主題目錄(Theme)建立一個Pages(專頁 / 頁面)命名為"tag-cloud.php" 其實文件名稱隨意的,你可以自設喜歡的名稱。
2. 文件加入以下頭部信息:
<?php
/*
Template Name: Tags Cloud
*/
?>
3. 進入 WordPress 管理後台 – 頁面 – 創建頁面,標題為標籤雲(可以自己起名)內容不要填,右側可以選擇模板,選擇 Tags Cloud 即可
4. 標簽頁創建成功。
OK... 加入以下代碼
1. 隨機顏色
<?php
$html = '<ul class="post_tags">';
foreach (get_tags( array('number' => 50, 'orderby' => 'count', 'order' => 'DESC', 'hide_empty' => false) ) as $tag){
$color = dechex(rand(0,16777215));
$tag_link = get_tag_link($tag->term_id);
$html .= "<li><a href='{$tag_link}' title='{$tag->name}' class='{$tag->slug}' style='color:#{$color}'>";
$html .= "{$tag->name} ({$tag->count})</a></li>";
}
$html .= '</ul>';
echo $html;
?>
2. 自訂顏色
<?php
$html = '<div class="page-tag">';
foreach (get_tags( array('number' => 50, 'orderby' => 'count', 'order' => 'DESC', 'hide_empty' => false) ) as $tag){
$color_array = array('tag-color-a', 'tag-color-b', 'tag-color-c', 'tag-color-d', 'tag-color-e', 'tag-color-f', 'tag-color-g', 'tag-color-h', 'tag-color-i', 'tag-color-j', 'tag-color-k', 'tag-color-l', 'tag-color-m', 'tag-color-n', 'tag-color-o', 'tag-color-p', 'tag-color-q', 'tag-color-r', 'tag-color-s', 'tag-color-t');
$color = $color_array[rand(0, 19)];
$tag_link = get_tag_link($tag->term_id);
$html .= "<a href='{$tag_link}' title='{$tag->name}'>";
$html .= "<span class='{$color}'>{$tag->name}</span><sup>({$tag->count})</sup></a> ";
}
$html .= '</div>';
echo $html;
?>
說明:
1. 數字 50 為顯示標籤的數量,如果無限制設為 0 即可。
2. 控制標籤是按標簽所含的文章數從多到少排序,如果你想按名稱方式排序,請將 count 改成 name 即可。
3. 不要顏色刪除 $color = dechex(rand(0,16777215)); 及 style='color:#{$color}' 代碼。
4. 代碼 tag-color-a、tag-color-b、tag-color-c 等等…需要配合 css 代碼。如:
.tag-color-a {
color: #FCFCFC;
}
5. 以上代碼都顯示包含文章數為 0 的標籤,如果你不想顯示空標簽,請將 false 改成 true 然後在主題目錄下的 style.css 中添加 css 樣式(以下代碼僅供參考):
ul.post_tags li {
display:block;
width:23%;
list-style:none;
background:none;
float:left;
}
WP 顯示所有標簽 - 官方版
<?php
$tags = get_tags();
$html = '<div class="tagcloud">';
foreach ($tags as $tag) {
$tag_link = get_tag_link($tag->term_id);
$html .= "<a href='{$tag_link}' title='{$tag->name} Tag' class='{$tag->slug}'>";
$html .= "{$tag->name}</a>";
}
$html .= '</div>';
echo $html;
?>
<?php wp_tag_cloud(); ?>
<?php wp_tag_cloud('smallest=12&largest=18&unit=px&number=0&orderby=count&order=DESC'); ?>
代碼詮釋:
smallest 表示標簽的最小字號
largest 表示最大字號
unit=px 表示字體使用像素單位
number=0 表示顯示所有標簽,如果為40,表示顯示40個
orderby=count 表示按照標簽所關聯的文章數來排列
order=DESC 表示降序排序(ASC表示升序排序,DESC表示降序排序)
官方說明:get_tags()
Example: 標籤雲
預覽效果Demo▼
1. WP當前分類顯示所屬標籤