get_ancestors

Get an array of ancestor IDs for a given object.

Description

(array) get_ancestors( (int) $object_id = 0, (string) $object_type = '', (string) $resource_type = '' ); 

Returns (array)

An array of ancestors from lowest to highest in the hierarchy.

Parameters (3)

0. $object_id — Optional. (int)
The ID of the object. Default 0.
1. $object_type — Optional. (string) => ''
The type of object for which we'll be retrieving ancestors. Accepts a post type or a taxonomy name. Default empty.
2. $resource_type — Optional. (string) => ''
Type of resource $object_type is. Accepts post_type or taxonomy.. Default empty.

Usage

  1. if ( !function_exists( 'get_ancestors' ) ) { 
  2. require_once ABSPATH . WPINC . '/taxonomy.php'; 
  3.  
  4. // Optional. The ID of the object. Default 0. 
  5. $object_id = -1; 
  6.  
  7. // Optional. The type of object for which we'll be retrieving 
  8. // ancestors. Accepts a post type or a taxonomy name. Default empty. 
  9. $object_type = ''; 
  10.  
  11. // Optional. Type of resource $object_type is. Accepts 'post_type' 
  12. // or 'taxonomy'. Default empty. 
  13. $resource_type = ''; 
  14.  
  15. // NOTICE! Understand what this does before running. 
  16. $result = get_ancestors($object_id, $object_type, $resource_type); 
  17.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/taxonomy.php  
  1. function get_ancestors( $object_id = 0, $object_type = '', $resource_type = '' ) { 
  2. $object_id = (int) $object_id; 
  3.  
  4. $ancestors = array(); 
  5.  
  6. if ( empty( $object_id ) ) { 
  7.  
  8. /** This filter is documented in wp-includes/taxonomy.php */ 
  9. return apply_filters( 'get_ancestors', $ancestors, $object_id, $object_type, $resource_type ); 
  10.  
  11. if ( ! $resource_type ) { 
  12. if ( is_taxonomy_hierarchical( $object_type ) ) { 
  13. $resource_type = 'taxonomy'; 
  14. } elseif ( post_type_exists( $object_type ) ) { 
  15. $resource_type = 'post_type'; 
  16.  
  17. if ( 'taxonomy' === $resource_type ) { 
  18. $term = get_term($object_id, $object_type); 
  19. while ( ! is_wp_error($term) && ! empty( $term->parent ) && ! in_array( $term->parent, $ancestors ) ) { 
  20. $ancestors[] = (int) $term->parent; 
  21. $term = get_term($term->parent, $object_type); 
  22. } elseif ( 'post_type' === $resource_type ) { 
  23. $ancestors = get_post_ancestors($object_id); 
  24.  
  25. /** 
  26. * Filters a given object's ancestors. 
  27. * @since 3.1.0 
  28. * @since 4.1.1 Introduced the `$resource_type` parameter. 
  29. * @param array $ancestors An array of object ancestors. 
  30. * @param int $object_id Object ID. 
  31. * @param string $object_type Type of object. 
  32. * @param string $resource_type Type of resource $object_type is. 
  33. */ 
  34. return apply_filters( 'get_ancestors', $ancestors, $object_id, $object_type, $resource_type );