get_ancestors()
云策文档标注
概述
get_ancestors() 函数用于获取指定对象的祖先ID数组,支持文章类型和分类法。它通过递归或调用相关函数来构建从最低到最高层级的ID列表。
关键要点
- 函数返回一个整数数组,包含从最低到最高层级的祖先ID。
- 参数包括 $object_id(对象ID,默认0)、$object_type(对象类型,如文章类型或分类法名称,默认空)和 $resource_type(资源类型,如 'post_type' 或 'taxonomy',默认空)。
- 如果 $resource_type 未指定,函数会根据 $object_type 自动判断资源类型。
- 对于分类法资源,使用 get_term() 递归获取父项ID;对于文章类型资源,调用 get_post_ancestors()。
- 应用了 'get_ancestors' 过滤器,允许开发者修改祖先数组。
代码示例
// 示例:获取分类法术语的祖先ID
$ancestors = get_ancestors(208, 'category', 'taxonomy');
// 返回数组,例如 [23, 6],表示从 Mystery 到 Books 的祖先ID。注意事项
- 确保 $object_id 有效,否则可能返回空数组。
- 使用前需验证 $object_type 是否已注册,以避免错误。
- 注意资源类型的自动推断逻辑,可能影响性能或结果准确性。
原文内容
Gets an array of ancestor IDs for a given object.
Parameters
$object_idintoptional-
The ID of the object. Default 0.
$object_typestringoptional-
The type of object for which we’ll be retrieving ancestors. Accepts a post type or a taxonomy name. Default empty.
$resource_typestringoptional-
Type of resource $object_type is. Accepts
'post_type'or'taxonomy'. Default empty.
Source
function get_ancestors( $object_id = 0, $object_type = '', $resource_type = '' ) {
$object_id = (int) $object_id;
$ancestors = array();
if ( empty( $object_id ) ) {
/** This filter is documented in wp-includes/taxonomy.php */
return apply_filters( 'get_ancestors', $ancestors, $object_id, $object_type, $resource_type );
}
if ( ! $resource_type ) {
if ( is_taxonomy_hierarchical( $object_type ) ) {
$resource_type = 'taxonomy';
} elseif ( post_type_exists( $object_type ) ) {
$resource_type = 'post_type';
}
}
if ( 'taxonomy' === $resource_type ) {
$term = get_term( $object_id, $object_type );
while ( ! is_wp_error( $term ) && ! empty( $term->parent ) && ! in_array( $term->parent, $ancestors, true ) ) {
$ancestors[] = (int) $term->parent;
$term = get_term( $term->parent, $object_type );
}
} elseif ( 'post_type' === $resource_type ) {
$ancestors = get_post_ancestors( $object_id );
}
/**
* Filters a given object's ancestors.
*
* @since 3.1.0
* @since 4.1.1 Introduced the `$resource_type` parameter.
*
* @param int[] $ancestors An array of IDs of object ancestors.
* @param int $object_id Object ID.
* @param string $object_type Type of object.
* @param string $resource_type Type of resource $object_type is.
*/
return apply_filters( 'get_ancestors', $ancestors, $object_id, $object_type, $resource_type );
}
Hooks
- apply_filters( ‘get_ancestors’, int[] $ancestors, int $object_id, string $object_type, string $resource_type )
-
Filters a given object’s ancestors.
Skip to note 3 content
Codex
Given the following category hierarchy (with IDs):
– Books (6)
— Fiction (23)
—– Mystery (208)
returns:
Array
(
[0] => 23
[1] => 6
)
Skip to note 4 content
Codex
Given the a page hierarchy (with IDs):
– About (447)
— Child Page (448)
returns:
Array
(
[0] => 447
)