get_page_hierarchy()
云策文档标注
概述
get_page_hierarchy() 函数用于将页面按父子关系排序,生成一个扁平列表,其中子页面紧跟在父页面之后。它通过辅助结构处理父子关系,时间复杂度为 O(N)。
关键要点
- 函数接受一个 WP_Post 数组(引用传递)和可选的父页面 ID 参数,返回以 ID 为键、页面名称为值的数组,按层次结构排列。
- 内部使用 _page_traverse_name() 函数遍历子页面,并依赖于 $children 数组来存储父子关系。
- 函数从 WordPress 2.0.0 版本引入,常用于 WP_Rewrite::page_uri_index() 等场景,以处理页面 URI 索引。
代码示例
function get_page_hierarchy( &$pages, $page_id = 0 ) {
if ( empty( $pages ) ) {
return array();
}
$children = array();
foreach ( (array) $pages as $p ) {
$parent_id = (int) $p->post_parent;
$children[ $parent_id ][] = $p;
}
$result = array();
_page_traverse_name( $page_id, $children, $result );
return $result;
}注意事项
- 返回的数组键为页面 ID,值为页面标题,不包含缩进或其他视觉指示符来表示父子关系。
- 用户贡献的笔记指出,函数输出的是原始页面标题,开发者需自行处理层次结构的显示。
原文内容
Orders the pages with children under parents in a flat list.
Description
It uses auxiliary structure to hold parent-children relationships and runs in O(N) complexity
Parameters
$pagesWP_Post[]required-
Posts array (passed by reference).
$page_idintoptional-
Parent page ID. Default 0.
Source
function get_page_hierarchy( &$pages, $page_id = 0 ) {
if ( empty( $pages ) ) {
return array();
}
$children = array();
foreach ( (array) $pages as $p ) {
$parent_id = (int) $p->post_parent;
$children[ $parent_id ][] = $p;
}
$result = array();
_page_traverse_name( $page_id, $children, $result );
return $result;
}
Changelog
| Version | Description |
|---|---|
| 2.0.0 | Introduced. |
Skip to note 2 content
jon
get_page_hierarchy() returns an ID=>page_title array: the Key is ID of a Page, and the Value is the Page’s Title.
The Title is not modified by indentation or other means to indicate a Child Page immediately below its Parent Page.