这篇文章介绍的方法比较单一,可能有些时候我们还要获取指定分类及其所有子分类的文章数,本文将为你讲解如何实现这样的功能。
首先,定义实现函数,将以下php代码复制到当前主题的functions.php中:
function aye_get_cat_postcount($id) {
// 获取当前分类信息
$cat = get_category($id);
// 当前分类文章数
$count = (int) $cat->count;
// 获取当前分类所有子孙分类
$tax_terms = get_terms('category', array('child_of' => $id));
foreach ($tax_terms as $tax_term) {
// 子孙分类文章数累加
$count +=$tax_term->count;
}
return $count;
}
使用方法
在需要显示文章数量的地方加入下面代码即可。
<?php echo aye_get_cat_postcount(123); ?>