Skip to content

Instantly share code, notes, and snippets.

@s3rgiosan
Last active December 16, 2022 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save s3rgiosan/5fcb25357cd990ddf31c0dd1db8bc2f6 to your computer and use it in GitHub Desktop.
Save s3rgiosan/5fcb25357cd990ddf31c0dd1db8bc2f6 to your computer and use it in GitHub Desktop.
A collection of helper functions for terms.
/**
* Returns the terms associated with the given object, hierarchically structured.
*
* @param array $object_id The ID of the object to retrieve.
* @param string|string[] $taxonomies The taxonomy names to retrieve terms from.
* @return array
*/
function get_object_hierarchical_terms( $object_id, $taxonomies ) {
// Retrieve the terms.
$terms = wp_get_object_terms( $object_id, $taxonomies );
$hierarchical_terms = [];
foreach ( $terms as $term ) {
if ( $term->parent > 0 ) {
continue;
}
$term_id = $term->term_id;
$hierarchical_terms[ $term_id ] = $term;
$child_terms = collect_terms( $term_id, $terms );
if ( ! empty( $child_terms ) ) {
$hierarchical_terms[ $term_id ]->children = $child_terms;
}
}
return $hierarchical_terms;
}
/**
* Collects an array of terms into an organised collection.
*
* @param int $parent_id The parent term ID.
* @param array $terms Array of terms.
* @return array
*/
function collect_terms( $parent_id, $terms ) {
$children = [];
foreach ( $terms as $term ) {
if ( $term->parent !== $parent_id ) {
continue;
}
$term_id = $term->term_id;
$children[ $term_id ] = $term;
$child_terms = collect_terms( $term_id, $terms );
if ( ! empty( $child_terms ) ) {
$children[ $term_id ]->children = $child_terms;
}
}
return $children;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment