标签云函数功能与分类法支持
wp_tag_cloud() 主要用于生成标签云,依据各标签关联文章的数量来设定字体大小与排序规则。自2.8版本起,引入了分类法(taxonomy)参数,使得除了传统标签外,分类目录及其他自定义分类法也能作为“云”的内容进行展示。
默认用法与参数配置说明
基本用法
<?php wp_tag_cloud( $args ); ?>
默认调用方式
<?php $args = array( 'smallest' => 8, 'largest' => 22, 'unit' => 'pt', 'number' => 45, 'format' => 'flat', 'separator' => "\n", 'orderby' => 'name', 'order' => 'ASC', 'exclude' => null, 'include' => null, 'topic_count_text_callback' => default_topic_count_text, 'link' => 'view', 'taxonomy' => 'post_tag', 'echo' => true, 'child_of' => null(see Note!) ); ?>
注意:child_of并非wp_tag_cloud 数组的直接键名,但该函数内部调用了wp_parse_args() 和get_terms() ,因此可通过get_terms() 传入所有支持的数组键值。
未指定参数时的默认输出表现如下:
- smallest —— 出现频率最低的标签最小字号为8
- largest —— 出现频率最高的标签最大字号为22
- unit —— 字号单位默认为'pt'
- number —— 最多显示45个标签
- format —— 以平面结构展示,标签间以空格分隔
- separator —— 用于设置标签间的分隔符
- orderby —— 默认按标签名称排序
- order —— 默认升序排列
- exclude —— 默认不排除任何标签
- include —— 默认包含所有标签
- topic_count_text_callback —— 使用default_topic_count_text函数处理计数文本
- link —— 标签默认可点击
- taxonomy —— 默认基于文章标签构建云
- echo —— 默认直接输出结果
自定义标签读取与样式修改
由于默认方法将样式逻辑内嵌,定制性较差。若需自定义读取标签并调整展示样式,操作十分简便。以下示例展示了如何利用get_tags函数实现这一目标:
$html = '';
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 .= "name} Tag' class='{$tag->slug}' style='color:#{$color}'>";
$html .= "{$tag->name} ({$tag->count})";
}
$html .= '';
echo $html;
随机获取标签的SQL实现方案
若需在首页随机展示标签,可使用如下代码。但此做法可能对SEO产生不利影响,建议谨慎采用。
//获取随机标签
function get_rand_tags()
{
global $post, $wpdb;
$sql = "SELECT * FROM {$wpdb->prefix}terms wt INNER JOIN {$wpdb->prefix}term_taxonomy wtt on wt.term_id=wtt.term_id where wtt.taxonomy='post_tag' ORDER BY RAND() LIMIT 20";
$related_posts = $wpdb->get_results($sql);
$html = '';
foreach($related_posts as $tag)
{
$color = dechex(rand(0,16777215));
$tag_link = get_tag_link($tag->term_id);
$html .= "name} Tag' class='{$tag->slug}' style='color:#{$color}'>";
$html .= "{$tag->name} ({$tag->count})";
}
$html .= '';
echo $html;
}
试图通过修改get_tags函数的参数来获取随机标签并不奏效(笔者未能成功,欢迎指正)。最终解决方案是通过SQL语句连接数据表查询得出。
总结
以上内容即为本文的全部知识点,期望能为您的学习或工作提供参考,感谢对本站的支持。如需了解更多相关信息,请参阅下方相关链接。