格物往事

无插件实现 wordpress 彩色标签云效果

一、随机颜色

将以下代码放入主题包 functions.php 文件内:

1
2
3
4
5
6
7
8
9
10
11
12
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);

第8行代码”$color=dechex(rand(0,16777215));”:作用是定义标签随机颜色的十进制数值范围,0 等于 #000000,16777215 等于 #ffffff。你可以使用进制换算工具换算后修改这行代码,改变颜色范围。

在主题需要的地方加入以下代码:

1
<?php wp_tag_cloud('smallest=8&largest=24&number=50'); ?>

代码说明:

KO!

from:http://hezi.info/share/wordpress/wordpress-colore-tag.html

二、自定义颜色

1
2
3
4
5
6
7
8
9
10
11
function colorCloudCallback($matches) {
$tag_link=$matches[1];
/*颜色集合*/
$colorFull = array(‘#999′,’#D8D9A4′,’#9BB’,'#EB9′,’#a3c159′,’#FEC42D’,'#6C8C37′,
‘#c2dc15′,’#3371A3′,’#888′,’#00ccff’,'#FF8080′);
$color=$colorFull[ mt_rand(0, count($colorFull) - 1)];
$pattern = ‘/style=(\’|\”)(.*)(\’|\”)/i’;
$tag_link= preg_replace($pattern, “style=\”color:{$color};$2;\”", $tag_link);
return “<a $tag_link>”;
}
add_filter(‘wp_tag_cloud’, ‘colorCloud’, 1);
退出移动版