WordPress.org

Make WordPress Core

Ticket #12908: get_term_ancestors.diff

File get_term_ancestors.diff, 1.7 KB (added by scribu, 8 years ago)

Introduce get_term_ancestors() and use in cat_is_ancestor_of()

  • wp-includes/category.php

     
    209209function cat_is_ancestor_of( $cat1, $cat2 ) {
    210210        if ( ! isset($cat1->term_id) )
    211211                $cat1 = &get_category( $cat1 );
    212         if ( ! isset($cat2->parent) )
     212        if ( ! isset($cat2->term_id) )
    213213                $cat2 = &get_category( $cat2 );
    214214
    215         if ( empty($cat1->term_id) || empty($cat2->parent) )
     215        if ( empty($cat1->term_id) || empty($cat2->term_id) )
    216216                return false;
    217         if ( $cat2->parent == $cat1->term_id )
    218                 return true;
    219217
    220         return cat_is_ancestor_of( $cat1, get_category( $cat2->parent ) );
     218        return in_array($cat1->term_id, get_term_ancestors($cat2->term_id, 'category'));
    221219}
    222220
    223221
  • wp-includes/taxonomy.php

     
    584584}
    585585
    586586/**
     587 * Get the list of all ancestors of a certain term
     588 *
     589 * @package WordPress
     590 * @subpackage Taxonomy
     591 * @since 3.1.0
     592 *
     593 * @uses get_terms()
     594 *
     595 * @param string $taxonomy Taxonomy Name
     596 * @return array List of ancestor ids, from lowest to highest in the hierarchy
     597 */
     598function get_term_ancestors($term_id, $taxonomy) {
     599        if ( !is_taxonomy_hierarchical($taxonomy) )
     600                return array();
     601
     602        $parents = get_terms($taxonomy, array('get' => 'all', 'orderby' => 'id', 'fields' => 'id=>parent'));
     603
     604        $ancestors = array();
     605        while ( $parents[$term_id] > 0 )
     606                $term_id = $ancestors[] = $parents[$term_id];
     607
     608        return $ancestors;
     609}
     610
     611/**
    587612 * Get sanitized Term field.
    588613 *
    589614 * Does checks for $term, based on the $taxonomy. The function is for contextual