WordPress添加彩色標簽雲

11.調用標簽雲22.添加彩色功能33.制作標簽雲頁面44.邊欄中調用標簽雲

標簽雲是很多WordPress主題都有的一個主題元素,今天就講講如何為你的主題添加彩色標簽雲,包括邊欄調用和頁面調用。

1.調用標簽雲

我們可以使用 wp_tag_cloud() 函數實現標簽雲的調用。比如下面的樣例:

1
<?php wp_tag_cloud('smallest=12&largest=18&unit=px&number=0&orderby=count&order=DESC');?>

<?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表示降序排序)

更多 wp_tag_cloud() 參數,請參考 WordPress文檔 wp tag cloud

2.添加彩色功能

根據上面的參數,你已經可以調用出標簽雲瞭,將下面的代碼添加到主題的 functions.php 的最後一個 ?> 前面即可實現彩色:

1
2
3
4
5
6
7
8
9
10
11
12
13
//邊欄彩色標簽
function colorCloud($text) {
	$text = preg_replace_callback('|<a (.+?)>|i','colorCloudCallback', $text);
	return $text;
}
function colorCloudCallback($matches) {
	$text = $matches[1];
	$color = dechex(rand(0,16777215));
	$pattern = '/style=(\'|\”)(.*)(\'|\”)/i';
	$text = preg_replace($pattern, "style=\"color:#{$color};$2;\"", $text);
	return "<a $text>";
}
add_filter('wp_tag_cloud', 'colorCloud', 1);

//邊欄彩色標簽
function colorCloud($text) {
$text = preg_replace_callback(‘|<a (.+?)>|i’,’colorCloudCallback’, $text);
return $text;
}
function colorCloudCallback($matches) {
$text = $matches[1];
$color = dechex(rand(0,16777215));
$pattern = ‘/style=(\’|\”)(.*)(\’|\”)/i’;
$text = preg_replace($pattern, "style=\"color:#{$color};$2;\"", $text);
return "<a $text>";
}
add_filter(‘wp_tag_cloud’, ‘colorCloud’, 1);

3.制作標簽雲頁面

你可以看看WordPress大學的標簽雲頁面:https://www.wpdaxue.com/tags

1)復制你主題的 page.php 文件,在該文件的頂部添加:

1
2
3
4
5
<?php
/*
Template Name: Tags
*/
?>

<?php
/*
Template Name: Tags
*/
?>

2)使用下面的代碼替換page.php中的 <?php the_content(); ?> :

1
<?php wp_tag_cloud('smallest=12&largest=18&unit=px&number=0&orderby=count&order=DESC');?>

<?php wp_tag_cloud(‘smallest=12&largest=18&unit=px&number=0&orderby=count&order=DESC’);?>

3)該頁面一般不需要評論功能,刪除 page.php 中下面的代碼:

1
<?php if (comments_open()) comments_template( '', true ); ?>

<?php if (comments_open()) comments_template( ”, true ); ?>

4)你還可以根據自己的需要,刪除page.php中的某些功能,最後將該文件另存為 page-tags.php ,這樣,一個標簽雲模板就做好瞭。

5)訪問 WP後臺-頁面-新建頁面,頁面名稱自己填,隻需要在 頁面屬性 中,選擇 tags 模板即可:

wpdaxue.com-201211113

4.邊欄中調用標簽雲

你可以使用下面的函數調用,具體的修改方法,就靠你自己折騰主題瞭:

1
<?php wp_tag_cloud('smallest=12&largest=18&unit=px&number=20');?>

<?php wp_tag_cloud(‘smallest=12&largest=18&unit=px&number=20’);?>

不過,一般制作比較規范的WordPress主題,都支持 Widget小工具,你可以在 WP後臺-外觀-小工具 中查看是否支持 標簽雲小工具。

說明:本文隻是告訴你如何實現彩色標簽雲,以及如何調用。但是具體的樣式,就要靠你自己通過CSS代碼實現瞭。

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *