Typecho 统计并展示每个分类文章数量
需求
主页面分类部分,统计每个分类下的文章数量,保持分类层级,后跟该分类下的文章数量。
处理
通过修改外观主题中的 sidebar.php 文件中的分类部分,实现统计并展示分类下的文章数量。
通过控制台编辑:当前默认分类配置(控制台 -> 外观 -> 编辑当前外观 -> sidebar.php 文件中)
当前配置
当前默认分类配置,控制台 -> 外观 -> 编辑当前外观 -> sidebar.php 文件中
<?php if (!empty($this->options->sidebarBlock) && in_array('ShowCategory', $this->options->sidebarBlock)): ?>
<section class="widget">
<h3 class="widget-title"><?php _e('分类'); ?></h3>
<?php \Widget\Metas\Category\Rows::alloc()->listCategories('wrapClass=widget-list'); ?>
</section>
<?php endif; ?>目前的主题使用了 Typecho 内置的分类调用方法:
<?php \Widget\Metas\Category\Rows::alloc()->listCategories('wrapClass=widget-list'); ?>这个方法会渲染分类列表,但默认不会显示每个分类下的文章数量。
调整外观
保留目录分级+显示文章数量
你可以使用 Typecho 提供的递归方法自己构建层级关系,示例如下:
<?php
function listCategoriesWithCount($parent = 0)
{
$categories = Typecho_Widget::widget('Widget_Metas_Category_List');
$categories->to($cat);
// 创建一个树结构
$tree = [];
while ($cat->next()) {
$tree[$cat->parent][] = clone $cat;
}
// 递归输出
$render = function($parentId) use (&$tree, &$render) {
if (empty($tree[$parentId])) return;
echo '<ul class="widget-list">';
foreach ($tree[$parentId] as $category) {
echo '<li>';
echo '<a href="' . $category->permalink . '">' . $category->name . ' (' . $category->count . ')</a>';
// 递归子分类
$render($category->mid);
echo '</li>';
}
echo '</ul>';
};
$render($parent);
}
?>
<section class="widget">
<h3 class="widget-title"><?php _e('分类'); ?></h3>
<?php listCategoriesWithCount(); ?>
</section>
加入进去
<?php if (!empty($this->options->sidebarBlock) && in_array('ShowCategory', $this->options->sidebarBlock)): ?>
<?php
function listCategoriesWithCount($parent = 0)
{
$categories = Typecho_Widget::widget('Widget_Metas_Category_List');
$categories->to($cat);
// 创建一个树结构
$tree = [];
while ($cat->next()) {
$tree[$cat->parent][] = clone $cat;
}
// 递归输出
$render = function($parentId) use (&$tree, &$render) {
if (empty($tree[$parentId])) return;
echo '<ul class="widget-list">';
foreach ($tree[$parentId] as $category) {
echo '<li>';
echo '<a href="' . $category->permalink . '">' . $category->name . ' (' . $category->count . ')</a>';
// 递归子分类
$render($category->mid);
echo '</li>';
}
echo '</ul>';
};
$render($parent);
}
?>
<section class="widget">
<h3 class="widget-title"><?php _e('分类'); ?></h3>
<?php listCategoriesWithCount(); ?>
</section>
<?php endif; ?>结果
结果符合预期了
分类
随笔 (6)
监控 (1)
日志收集 (6)
自动化 (1)
网络技术 (1)
Iptables (0)
编程语言 (0)
Golang (0)
Python (0)
Linux (8)
Shell (0)
CI_CD (1)
Kubernetes (0)
Nginx (8)
Docker (5)
Windows (1)对比原生,达到了想要的效果
分类
随笔
监控
日志收集
自动化
网络技术
Iptables
编程语言
Golang
Python
Linux
Shell
CI_CD
Kubernetes
Nginx
Docker
Windows