Using WordPress ‘get_ancestors()’ PHP function

The get_ancestors() WordPress PHP function retrieves an array of ancestor IDs for a given object, such as a post or taxonomy term.

Usage

get_ancestors( $object_id, $object_type, $resource_type );

Example

Input: get_ancestors( 208, 'category' );

Output: Array ( [0] => 23 [1] => 6 )

Parameters

  • $object_id (int) – Optional. The ID of the object. Default is 0.
  • $object_type (string) – Optional. The type of object for which we’ll be retrieving ancestors. Accepts a post type or a taxonomy name. Default is ”.
  • $resource_type (string) – Optional. Type of resource $object_type is. Accepts ‘post_type’ or ‘taxonomy’. Default is ”.

More information

See WordPress Developer Resources: get_ancestors()

Examples

Get category ancestors

Retrieve the ancestor IDs of a category with ID 208.

$ancestor_ids = get_ancestors( 208, 'category' );
print_r( $ancestor_ids );

Get page ancestors

Retrieve the ancestor IDs of a page with ID 448.

$ancestor_ids = get_ancestors( 448, 'page' );
print_r( $ancestor_ids );

Get custom post type ancestors

Retrieve the ancestor IDs of a custom post type object with ID 1024.

$ancestor_ids = get_ancestors( 1024, 'my_custom_post_type', 'post_type' );
print_r( $ancestor_ids );

Get custom taxonomy term ancestors

Retrieve the ancestor IDs of a custom taxonomy term with ID 56.

$ancestor_ids = get_ancestors( 56, 'my_custom_taxonomy', 'taxonomy' );
print_r( $ancestor_ids );

Display ancestors as a list

Retrieve the ancestor IDs of a category with ID 208 and display them as a list.

$ancestor_ids = get_ancestors( 208, 'category' );

echo '<ul>';
foreach ( $ancestor_ids as $ancestor_id ) {
    echo '<li>' . get_cat_name( $ancestor_id ) . '</li>';
}
echo '</ul>';