在 Typecho 中创建标签云(Tag Cloud)可以通过 Widget_Metas_Tag_Cloud 组件来实现。标签云是一种以字体大小或颜色显示标签流行度的方式,通常用于博客的侧边栏或底部,以便用户能够快速找到热门话题。
下面是如何在你的主题中添加一个简单的标签云:
✅ 实现标签云
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| <?php
$this->widget('Widget_Metas_Tag_Cloud', 'sort=count&ignoreZeroCount=1&desc=1&limit=50')->to($tags);
?>
<?php if($tags->have()): ?>
<?php while($tags->next()): ?>
<a href="<?php $tags->permalink(); ?>" style="font-size:<?php echo rand(12, 24); ?>px;" title='<?php $tags->count(); ?> 篇文章'>
<?php $tags->name(); ?>
</a>
<?php endwhile; ?>
<?php else: ?>
暂无标签。
<?php endif; ?>
|
🧠 说明
Widget_Metas_Tag_Cloud:这个组件用来生成标签云。
'sort=count&ignoreZeroCount=1&desc=1&limit=50':参数解释如下:
sort=count:按照文章数量排序。
ignoreZeroCount=1:忽略没有文章的标签。
desc=1:降序排列(从大到小)。
limit=50:限制显示的标签数量为50个。
rand(12, 24):随机生成字体大小,使标签云更加多样化。你可以根据需要调整范围。
$tags->count():获取该标签下的文章数量。
💡 改进样式
为了使标签云看起来更好,可以添加一些 CSS 样式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| .tag-cloud a {
display: inline-block;
margin: 3px;
padding: 3px 6px;
color: #fff;
background-color: #888;
text-decoration: none;
border-radius: 3px;
}
.tag-cloud a:hover {
background-color: #555;
}
|
🛠️ 动态调整字体大小
如果你想让字体大小更准确地反映标签的重要性,可以根据标签关联的文章数动态计算字体大小:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| <?php while($tags->next()): ?>
<?php
$minFontSize = 12;
$maxFontSize = 30;
$minCount = 1;
$maxCount = max($tags->getAll(), function($item) { return $item['count']; });
$fontSize = ($tags->count - $minCount) / ($maxCount - $minCount) * ($maxFontSize - $minFontSize) + $minFontSize;
?>
<a href="<?php $tags->permalink(); ?>" style="font-size:<?php echo $fontSize; ?>px;" title='<?php $tags->count(); ?> 篇文章'>
<?php $tags->name(); ?>
</a>
<?php endwhile; ?>
|
注意:上述代码中的 $maxCount 需要你根据实际情况进行获取,可能需要对原始数据进行遍历以找出最大的文章数。此部分代码仅供参考,可能需要根据实际需求进行适当调整。