Skip to content

Instantly share code, notes, and snippets.

@ericpedia
Created August 3, 2011 13:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ericpedia/1122631 to your computer and use it in GitHub Desktop.
Save ericpedia/1122631 to your computer and use it in GitHub Desktop.
get top parents in wordpress
<?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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment