Paramètre

$taxonomy(string)requis

Nom de la taxonomie.

Retourne

(array) Un tableau d'id des termes enfants de la taxonomie donnée, un tableau vide si la taxonomie n'est pas hiérarchique.

Déclaration et structure de la fonction _get_term_hierarchy()

function _get_term_hierarchy( $taxonomy ) {
    if ( ! is_taxonomy_hierarchical( $taxonomy ) ) {
        return array();
    }
    $children = get_option( "{$taxonomy}_children" );

    if ( is_array( $children ) ) {
        return $children;
    }
    $children = array();
    $terms    = get_terms(
        array(
            'taxonomy'               => $taxonomy,
            'get'                    => 'all',
            'orderby'                => 'id',
            'fields'                 => 'id=>parent',
            'update_term_meta_cache' => false,
        )
    );
    foreach ( $terms as $term_id => $parent ) {
        if ( $parent > 0 ) {
            $children[ $parent ][] = $term_id;
        }
    }
    update_option( "{$taxonomy}_children", $children );

    return $children;
}
get_terms()

Retourne les termes pour une taxonomie donnée ou une liste de taxonomies.

is_taxonomy_hierarchical()

Détermine si la taxonomie est hiérarchique.

update_option()

Met à jour la valeur d'une option.

get_option()

Retourne une valeur d'option en fonction de son nom.

Où est utilisée la fonction _get_term_hierarchy() dans le CMS WordPress

Exemple

Parser une taxonomie pour obtenir ses termes enfants :
$taxonomy = 'category';
/** On récupère tous les termes de la taxonomie */
$terms = get_terms($taxonomy, array(
        "orderby"    => "count",
        "hide_empty" => false
    )
);

/** Get terms that have children */
$hierarchy = _get_term_hierarchy($taxonomy);

foreach($terms as $term) {
    // on passe si le terme est un enfant
    if($term->parent) {
      continue;
    }
    echo $term->name;

    /** Si le terme a un enfant */
      if($hierarchy[$term->term_id]) {
   
          foreach($hierarchy[$term->term_id] as $child) {
              /** On récupère l'objet du terme par sin id */
              $child = get_term($child, "category_list");
              echo '--'.$child->name;
          }
      }
  }

Sources

Codex WordPress : _get_term_hierarchy()

Autres fonctions dans le même fichier : wp-includes/taxonomy.php

Retour