get_ancestors()
Get an array of ancestor IDs for a given object.
Uses: get_post_ancestors(), get_term()
Used By: get_term_parents_list()
1 time — 0.00174 sec (very slow) | 50000 times — 0.95 sec (very fast) | PHP 7.2.5, WP 5.0.1
Hooks from the function
Return
Int[]
. An array of IDs of ancestors from lowest to highest in the hierarchy.
Usage
get_ancestors( $object_id, $object_type, $resource_type );
- $object_id(int)
- The ID of the object.
- $object_type(string)
- The type of object for which we'll be retrieving ancestors. Accepts a post type or a taxonomy name.
Default: '' - $resource_type(string)
- Type of resource $object_type is. Accepts 'post_type' or 'taxonomy'.
Default: ''
Examples
#1 Get the IDs of all parent elements of the taxonomy term
Suppose we have this category structure. The IDs are in brackets:
- Books (6)
- fiction (23)
- Ray Bradbury (208)
- fiction (23)
$ancestors = get_ancestors( 208, 'category' );
Now, the variable $ancestors will contain such an array:
Array ( [0] => 23 [1] => 6 )
#2 Get the IDs of all parent pages
Suppose, you need to get the IDs of the parent static pages, let's assume we have this structure:
- About site (447)
- Subsidiary page (448)
$ancestors = get_ancestors( 448, 'page' );
Now, the variable $ancestors will contain an array:
Array ( [0] => 447 )
#3 Get the ID of the topmost parent category
$ancestors = get_ancestors( 208, 'category' ); $top_cat_id = array_pop( $ancestors );
Changelog
Since 3.1.0 | Introduced. |
Since 4.1.0 | Introduced the $resource_type argument. |