要获取WordPress中分类及其子分类的文章数,您可以使用WordPress提供的内置函数和WP_Query来执行此任务。以下是一个示例代码,可以帮助您获取分类及其子分类的文章数:
<?php // 获取指定分类的分类对象(例如,分类ID为1) $category = get_category(1); // 获取分类及其所有子分类的ID $all_category_ids = get_term_children($category>term_id, 'category'); // 将当前分类的ID添加到数组中 $all_category_ids[] = $category>term_id; // 构建查询参数以获取这些分类的文章数 $args = array( 'category__in' => $all_category_ids, 'post_type' => 'post', // 文章类型 'post_status' => 'publish', // 发布状态 'posts_per_page' => 1, // 获取所有文章 ); // 使用WP_Query执行查询 $query = new WP_Query($args); // 获取文章数 $article_count = $query>post_count; // 显示文章数 echo '分类 "' . $category>name . '" 及其子分类共有 ' . $article_count . ' 篇文章。'; // 重置查询 wp_reset_postdata(); ?>
这段代码首先获取了指定分类的分类对象,然后使用get_term_children
函数获取该分类及其所有子分类的ID。接下来,它构建了一个WP_Query对象,用于查询这些分类的文章数。最后,它使用post_count
属性获取文章数,并将其显示在页面上。
请注意,您需要将示例中的category__in
参数值更改为您想要查询的分类的ID。此外,您可以根据需要自定义显示文章数的方式。