Custom Taxonomy – Modify Function to Get Child Category
Question
I am using these two functions which result in getting the top parent category of a custom taxonomy. These have been tested and work as expected.
However, now I am looking for a way to output the child category instead of the parent.
function get_term_top_most_parent( $term, $taxonomy ) {
// Start from the current term
$parent = get_term( $term, $taxonomy );
// Climb up the hierarchy until we reach a term with parent = '0'
while ( $parent->parent != '0' ) {
$term_id = $parent->parent;
$parent = get_term( $term_id, $taxonomy);
}
return $parent;
}
function get_top_parents( $taxonomy ) {
// get terms for current post
$terms = wp_get_object_terms( get_the_ID(), $taxonomy );
$top_parent_terms = array();
foreach ( $terms as $term ) {
//get top level parent
$top_parent = get_term_top_most_parent( $term, $taxonomy );
//check if you have it in your array to only add it once
if ( !in_array( $top_parent, $top_parent_terms ) ) {
$top_parent_terms[] = $top_parent;
}
}
// build output (the HTML is up to you)
foreach ( $top_parent_terms as $term ) {
//Add every term
$output = $term->slug;
}
return $output;
}
0
2 years
2020-12-16T15:10:34-05:00
2020-12-16T15:10:34-05:00 0 Answers
9 views
0
Leave an answer