函数文档

_get_term_hierarchy()

💡 云策文档标注

概述

_get_term_hierarchy() 函数用于获取指定分类法的子项作为术语ID数组。如果分类法不是层级结构,则返回空数组。

关键要点

  • 参数 $taxonomy 是必需的字符串,指定分类法名称。
  • 返回值是一个数组,包含子项术语ID,如果分类法非层级则返回空数组。
  • 函数首先检查分类法是否为层级结构,然后尝试从选项缓存中获取子项数据,若不存在则通过 get_terms() 查询并更新缓存。

代码示例

$taxonomy = "category";
$hierarchy = _get_term_hierarchy($taxonomy);
// 使用 $hierarchy 数组处理术语层级关系

注意事项

  • 此函数是内部函数,通常不直接用于主题或插件开发,建议使用更高级的API如 get_term_children()。
  • 依赖于 is_taxonomy_hierarchical() 和 get_option()/update_option() 进行缓存管理。

📄 原文内容

Retrieves children of taxonomy as term IDs.

Parameters

$taxonomystringrequired
Taxonomy name.

Return

array Empty if $taxonomy isn’t hierarchical or returns children as term IDs.

Source

function _get_term_hierarchy( $taxonomy ) {
	if ( ! is_taxonomy_hierarchical( $taxonomy ) ) {
		return array();
	}
	$children = get_option( "{$taxonomy}_children" );

	if ( is_array( $children ) ) {
		return $children;
	}
	$children = array();
	$terms    = get_terms(
		array(
			'taxonomy'               => $taxonomy,
			'get'                    => 'all',
			'orderby'                => 'id',
			'fields'                 => 'id=>parent',
			'update_term_meta_cache' => false,
		)
	);
	foreach ( $terms as $term_id => $parent ) {
		if ( $parent > 0 ) {
			$children[ $parent ][] = $term_id;
		}
	}
	update_option( "{$taxonomy}_children", $children );

	return $children;
}

Changelog

Version Description
2.3.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

       /** The taxonomy we want to parse */
       $taxonomy = "category";
       /** Get all taxonomy terms */
       $terms = get_terms($taxonomy, array(
               "orderby"    => "count",
               "hide_empty" => false
           )
       );
       /** Get terms that have children */
       $hierarchy = _get_term_hierarchy($taxonomy);
           /** Loop through every term */
           foreach($terms as $term) {
           //Skip term if it has children
           if($term->parent) {
             continue;
           }
             echo $term->name;
           /** If the term has children... */
             if($hierarchy[$term->term_id]) {
           /** display them */
           foreach($hierarchy[$term->term_id] as $child) {
           /** Get the term object by its ID */
           $child = get_term($child, "category_list");
                echo '--'.$child->name;
               }
            }
         }