Skip to content

Instantly share code, notes, and snippets.

@EricBusch
Last active June 27, 2023 03:38
Show Gist options
  • Save EricBusch/d4b80c5091a0cf854126 to your computer and use it in GitHub Desktop.
Save EricBusch/d4b80c5091a0cf854126 to your computer and use it in GitHub Desktop.
Make terms retrieved by wp_get_object_terms() organized hierarchically. [wordpress]
<?php
/**
* Make terms retrieved by wp_get_object_terms() organized hierarchically.
*
* Use this function instead of wp_get_object_terms() to get a hierarchically
* structured array or term data.
*
* This function takes the terms returned by wp_get_object_terms() and organizes
* them into a hierarchical array with the parent's children (and grandchildren)
* stored in nested arrays (within the 'children' item).
*
* @see wp_get_object_terms() for parameters.
*
* @return array $terms Hierarchilized $terms array.
*/
function get_object_terms_hierarchical( $object_ids, $taxonomies, $args = array() ) {
$tree = array();
$terms = wp_get_object_terms( $object_ids, $taxonomies, $args );
if ( ! empty( $terms ) ) {
foreach ( $terms as $term ) {
if ( $term->parent == 0 ) {
$tree[ $term->term_id ] = $term;
$tree[ $term->term_id ]->children = get_child_terms( $term->term_id, $terms );
}
}
}
return $tree;
}
/**
* Organizes the child terms.
*
* This is a recursive function.
*
* @param interval $parent_id The parent ID to retrieve the children terms of.
* @param array $terms The term data.
*
* @return array Returns nested child terms.
*/
function get_child_terms( $parent_id, $terms ) {
$children = array();
foreach ( $terms as $term ) {
if ( $term->parent == $parent_id ) {
$children[ $term->term_id ] = $term;
$children[ $term->term_id ]->children = get_child_terms( $term->term_id, $terms );
}
}
return $children;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment