wordpress根据父分类ID获取子分类的名称、别名等
建站知识 2025年7月28日
在WordPress中,要根据父分类ID获取子分类的名称、别名、描述、链接和文章数,可以通过get_categories()函数实现。该函数能查询分类信息,结合参数筛选出指定父分类的子分类,再提取所需字段。
代码示例
<?php
// 父分类ID(替换为你的父分类ID)
$parent_category_id = 666;
// 查询子分类
$child_categories = get_categories(array(
'parent' => $parent_category_id, // 仅获取指定父分类的子分类
'hide_empty' => false, // 可选:是否隐藏无文章的分类(true=隐藏,false=显示)
'orderby' => 'name', // 排序方式(name=按名称,ID=按ID等)
'order' => 'ASC' // 排序方向(ASC=升序,DESC=降序)
));
// 遍历子分类并输出信息
if (!empty($child_categories)) {
echo '<ul>';
foreach ($child_categories as $category) {
// 提取子分类信息
$name = $category->name; // 名称
$slug = $category->slug; // 别名
$description = $category->description; // 描述
$link = get_category_link($category->term_id); // 链接(需用分类ID获取)
$count = $category->count; // 文章数
// 输出信息(可根据需求调整格式)
echo '<li>';
echo '<strong>名称:</strong>' . esc_html($name) . '<br>';
echo '<strong>别名:</strong>' . esc_html($slug) . '<br>';
echo '<strong>描述:</strong>' . esc_html($description) . '<br>';
echo '<strong>链接:</strong><a href="' . esc_url($link) . '">' . esc_url($link) . '</a><br>';
echo '<strong>文章数:</strong>' . esc_html($count);
echo '</li>';
}
echo '</ul>';
} else {
echo '该父分类下没有子分类。';
}
?>
代码说明
参数设置
parent:指定父分类 ID,仅返回该分类的直接子分类(不包含孙子分类)。
hide_empty:控制是否显示无文章的分类(默认true,即隐藏)。
其他参数(如orderby)可根据需求调整排序方式。
字段提取
分类对象($category)包含多种属性,直接通过对象属性获取:
name:分类名称
slug:分类别名(URL 中显示的标识)
description:分类描述
count:该分类下的文章数量
链接需通过get_category_link($category->term_id)函数生成(传入分类 ID)。
安全处理
使用esc_html()过滤文本内容,防止 XSS 攻击;
使用esc_url()过滤链接,确保 URL 格式正确。
扩展说明
如果需要获取所有后代分类(包括子分类、孙子分类等),可将parent参数改为child_of,例如:
‘child_of’ => $parent_category_id
若需在模板文件(如category.php)中使用,可直接嵌入代码;若在主题函数(functions.php)中使用,建议封装为函数调用。