From b55b06e4666ef99802d76bd7a02b4305112fa807 Mon Sep 17 00:00:00 2001 From: scribu Date: Sat, 18 Sep 2010 19:20:16 +0000 Subject: [PATCH] Introduce get_ancestors(). Props filosofo. Fixes #12443 git-svn-id: https://develop.svn.wordpress.org/trunk@15631 602fd350-edb4-49c9-b593-d223f7449a82 --- wp-includes/taxonomy.php | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/wp-includes/taxonomy.php b/wp-includes/taxonomy.php index f830027ae1..73dc7554c4 100644 --- a/wp-includes/taxonomy.php +++ b/wp-includes/taxonomy.php @@ -2775,3 +2775,40 @@ function is_object_in_taxonomy($object_type, $taxonomy) { return false; } + +/** + * Get an array of ancestor IDs for a given object. + * + * @param int $object_id The ID of the object + * @param string $object_type The type of object for which we'll be retrieving ancestors. + * @return array of ancestors from lowest to highest in the hierarchy. + */ +function get_ancestors($object_id = 0, $object_type = '') { + $object_id = (int) $object_id; + + $ancestors = array(); + + if ( empty( $object_id ) ) { + return apply_filters('get_ancestors', $ancestors, $object_id, $object_type); + } + + if ( is_taxonomy_hierarchical( $object_type ) ) { + $term = get_term($object_id, $object_type); + while ( ! is_wp_error($term) && ! empty( $term->parent ) && ! in_array( $term->parent, $ancestors ) ) { + $ancestors[] = (int) $term->parent; + $term = get_term($term->parent, $object_type); + } + } elseif ( null !== get_post_type_object( $object_type ) ) { + $object = get_post($object_id); + if ( ! is_wp_error( $object ) && isset( $object->ancestors ) && is_array( $object->ancestors ) ) + $ancestors = $object->ancestors; + else { + while ( ! is_wp_error($object) && ! empty( $object->post_parent ) && ! in_array( $object->post_parent, $ancestors ) ) { + $ancestors[] = (int) $object->post_parent; + $object = get_post($object->post_parent); + } + } + } + + return apply_filters('get_ancestors', $ancestors, $object_id, $object_type); +}