修改wordpress标签云html结构实现彩色标签云

  •   
  • 4028
  • HTML
  • 2
  • super_dodo
  • 2015/10/29

实现非常简单:1.改html;2.改css
为什么要修改html结构呢?因为原始的标签云结构是

$a[] = <a class="tag-link-{$tag_id}" style="font-size: str_replace( ',', '.', ( $smallest + ( ( $count - $min_count ) * $font_step ) ) );" title="{$real_count}个话题" href="{$tag_link}">;{$tag_name}</a>;

而目标效果是字体大小固定,标签名称后面带此标签下文章的数量,所以要对结构作出一定的调整。这段html结构是写在wp-includes/category-template.php的函数wp_generate_tag_cloud()中的,我们可以直接修改函数的代码,坏处是每次升级的时候如果官方更新了这个文件,那么修改就要再做一次。
还有一种方法是用add_filter的方法在主题function.php中修改这段html结构,坏处是要损耗一小部分性能
。为了快速实现效果这里暂时用第一种方法,直接修改category-template.php的代码(砍掉了font-size,添加了标签文章数量):

$a[] = <a href='$tag_link' class='tag-link-$tag_id' title='" . esc_attr( call_user_func( $topic_count_text_callback, $real_count, $tag, $args ) ) . "'>$tag_name ($real_count)</a>";

然后在主题function.php中设置标签云

add_filter ('widget_tag_cloud_args', 'theme_tag_cloud_args');
function theme_tag_cloud_args ($args){
    $newargs = array(
        'number'     => 25, //显示个数
        'format'     => 'flat',//列表格式,可以是flat、list或array
        'separator'     => "\n", //分隔每一项的分隔符
        'orderby'     => 'count',//排序字段,可以是name或count
        'order'     => 'DESC', //升序或降序,ASC或DESC
        'exclude'     => null, //结果中排除某些标签
        'include'    => null, //结果中只包含这些标签
        'link'         => 'view',
        'taxonomy'    =>; array('post_tag','category'),
        'echo'         => true,
    );
    $return = array_merge( $args, $newargs);
    return $return;
}

最后在主题的style.css里添加css,其中颜色数目和值可根据个人喜好修改,效果就出来了

.tagcloud a{opacity: 0.80;filter: alpha(opacity=80);color: #FFF;display: inline-block;margin: 0 5px 5px 0;padding: 0 6px;line-height: 21px;text-decoration: none;border-radius: 1px;}
.tagcloud a:nth-child(9n){background-color: #4A4A4A;}
.tagcloud a:nth-child(9n+1){background-color: #428BCA;}
.tagcloud a:nth-child(9n+2){background-color: #5CB85C;}
.tagcloud a:nth-child(9n+3){background-color: #D9534F;}
.tagcloud a:nth-child(9n+4){background-color: #567E95;}
.tagcloud a:nth-child(9n+5){background-color: #B433FF;}
.tagcloud a:nth-child(9n+6){background-color: #00ABA9;}
.tagcloud a:nth-child(9n+7){background-color: #B37333;}
.tagcloud a:nth-child(9n+8){background-color: #FF6600;}

最后说明下wp_tag_cloud的参数
前几个不多说了,顾名思义,就是设置字体最大最小值、字体单位、显示数量、排序什么的。
重点说下后两个

format-(字符串)(可选)所显示的云的格式。
'flat' (默认值)标签被“separator”参数所定义的空格分隔
'list' 标签与class='wp-tag-cloud' 共同在UL中
'array' 标签在数组中,函数以数组方式返回标签云,以用在PHP中。注意:数组被返回,驻留在内存中而非显示。

taxonomy-(字符串或数组)(可选)用以生成云的分类法,可多选。
'post_tag' —— (默认值)将文章标签当作云的来源
'category' —— 用文章分类生成云
'link_category' —— 用链接分类目录生成云

愿得一人心,白首不相离。君记我一瞬,我念君半生。