我们在WordPress主题开发过程中,有的时候会需要做一个文章聚合页,比如显示所有新闻分类下二级新闻分类的名称及文章列表,如下图:
在 WordPress 主题开发中,获取某个指定分类下的所有子分类及其文章列表,标准做法是使用 WP_Term_Query + WP_Query。下面给你一套可直接用的模板代码,并附带常见变体。
一、获取指定分类下的所有子分类
假设你要获取 分类 ID = 10 的所有一级子分类:
$parent_cat_id = 10;
$child_categories = get_terms( array(
'taxonomy' => 'category',
'parent' => $parent_cat_id,
'hide_empty' => false, // true 表示只返回有文章的
) );
if ( ! empty( $child_categories ) && ! is_wp_error( $child_categories ) ) {
foreach ( $child_categories as $cat ) {
echo '<h3>' . esc_html( $cat->name ) . '</h3>';
}
}
✅ $cat->name:子分类名称
✅ $cat->term_id:子分类 ID
✅ $cat->slug:别名
二、获取每个子分类下的文章列表
在上面的循环中继续查文章:
if ( ! empty( $child_categories ) && ! is_wp_error( $child_categories ) ) {
foreach ( $child_categories as $cat ) {
echo '<h3>' . esc_html( $cat->name ) . '</h3>';
$args = array(
'post_type' => 'post',
'posts_per_page' => 5,
'cat' => $cat->term_id,
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
echo '<ul>';
while ( $query->have_posts() ) {
$query->the_post();
echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
}
echo '</ul>';
} else {
echo '<p>暂无文章</p>';
}
wp_reset_postdata();
}
}
三、递归获取「所有层级」子分类(可选)
如果你想要 包含孙子分类(多层):
function get_all_child_categories( $parent_id ) {
$children = get_terms( array(
'taxonomy' => 'category',
'parent' => $parent_id,
'hide_empty' => false,
) );
$result = array();
if ( ! empty( $children ) && ! is_wp_error( $children ) ) {
foreach ( $children as $child ) {
$result[] = $child;
$result = array_merge( $result, get_all_child_categories( $child->term_id ) );
}
}
return $result;
}
$all_childs = get_all_child_categories( 10 );
然后遍历 $all_childs,再用 WP_Query查文章即可。
四、按分类显示文章(含分页)
如果你希望 一个分类一个页面(SEO 更友好),可以在 taxonomy-category.php中直接使用:
$category = get_queried_object();
$args = array(
'post_type' => 'post',
'posts_per_page' => 10,
'cat' => $category->term_id,
);
$query = new WP_Query( $args );
五、常见错误排查
| 问题 | 原因 |
|---|---|
| 取不到子分类 | 分类没有子分类 / hide_empty=true |
| 文章不显示 | 文章状态不是 publish |
| 自定义文章类型 | 需要 'post_type' => 'your_cpt' |
| 自定义分类法 | 把 category改成你的 taxonomy |
六、推荐封装成函数(主题开发中更优雅)
function show_category_and_posts( $parent_id ) {
$cats = get_terms( array(
'taxonomy' => 'category',
'parent' => $parent_id,
) );
foreach ( $cats as $cat ) {
echo '<h3>' . esc_html( $cat->name ) . '</h3>';
// WP_Query 同上
}
}
调用:
show_category_and_posts( 10 );



湘公网安备43020002000238