Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
get top parents in wordpress
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