get_term_children()
云策文档标注
概述
get_term_children() 是一个递归函数,用于获取指定分类法中某个术语的所有子术语ID,并合并到一个数组中。仅适用于分层分类法。
关键要点
- 函数返回术语ID数组或WP_Error对象,若分类法不存在则返回WP_Error
- 参数包括必需的$term_id(整数)和$taxonomy(字符串)
- 如果术语在分类法中不存在,返回空数组
- 递归处理子术语,确保所有后代ID被包含
- 仅对分层分类法(如分类目录)有效
代码示例
$termchildren = get_term_children( $term_id, $taxonomy_name );
echo '<ul>';
foreach ( $termchildren as $child ) {
$term = get_term_by( 'id', $child, $taxonomy_name );
echo '<li><a href="' . get_term_link( $term ) . '">' . $term->name . '</a></li>';
}
echo '</ul>';注意事项
- 对于分类目录,$taxonomy参数应为'category';对于标签,应为'post_tag'
- 如果术语存在但无子术语,函数可能返回包含该术语ID的数组(取决于实现细节)
- 此函数替代了已弃用的get_category_children(),后者返回字符串而非数组
原文内容
Merges all term children into a single array of their IDs.
Description
This recursive function will merge all of the children of $term into the same array of term IDs. Only useful for taxonomies which are hierarchical.
Will return an empty array if $term does not exist in $taxonomy.
Parameters
$term_idintrequired-
ID of term to get children.
$taxonomystringrequired-
Taxonomy name.
Source
function get_term_children( $term_id, $taxonomy ) {
if ( ! taxonomy_exists( $taxonomy ) ) {
return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
}
$term_id = (int) $term_id;
$terms = _get_term_hierarchy( $taxonomy );
if ( ! isset( $terms[ $term_id ] ) ) {
return array();
}
$children = $terms[ $term_id ];
foreach ( (array) $terms[ $term_id ] as $child ) {
if ( $term_id === $child ) {
continue;
}
if ( isset( $terms[ $child ] ) ) {
$children = array_merge( $children, get_term_children( $child, $taxonomy ) );
}
}
return $children;
}
Changelog
| Version | Description |
|---|---|
| 2.3.0 | Introduced. |
Skip to note 4 content
Codex
A Basic Example
Used to get an array of children taxonomies and write them out with links in an unordered list.
'; foreach ( $termchildren as $child ) { $term = get_term_by( 'id', $child, $taxonomy_name ); echo '<li><a href="' . get_term_link( $child, $taxonomy_name ) . '">' . $term->name . '</a></li>'; } echo '</ul>'; ?>This would return something like.
<ul> <li><a href="link_to_term_page">Term 1</a></li> <li><a href="link_to_term_page">Term 2</a></li> </ul>Skip to note 5 content
jon
Categories and Tags are the two pre-defined Taxonomies. The Taxonomy Name, the second required parameter $taxonomy, is ‘category’ for Categories and ‘post_tag’ for Tags.
If replacing the deprecated function get_category_children() , which returns a String, note that get_term_children() returns an array of Category IDs if the second parameter $taxonomy is ‘category’.
Skip to note 6 content
Tunn
If the term exists in the taxonomy, but has no children, the term ID will be returned instead.