public
Created

get top parents in wordpress

  • Download Gist
gistfile1.aw
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
<?php
function get_term_top_most_parent($term_id, $taxonomy){
$parent = get_term_by( 'id', $term_id, $taxonomy);
while ($parent->parent != 0){
$parent = get_term_by( 'id', $term_id, $taxonomy);
}
return $parent;
}
// so once you have this function you can just loop over the results returned by wp_get_object_terms
 
function hey_top_parents($taxonomy) {
$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->ID, $taxonomy);
//check if you have it in your array to only add it once
if (!in_array($top_parent->ID,$top_parent_terms)){
$top_parent_terms[] = $top_parent;
}
}
 
// return the results
 
foreach ($top_parent_terms as $term) {
$r = '<a href="' . get_term_link($term->slug, $taxonomy) . '">' . $term->name . '</a>';
/* This line causes "Catchable fatal error: Object of class WP_Error could not be converted to string in /home/eric/public_html/wp-content/plugins/epi-plugin/epi-plugin.php on line 675" */
 
}
return $r;
 
} // End of top parents

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.