Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Get top-level parent term WordPress

  • SOLVED

This is from StackExchange—just trying to get a quick answer here:

How do I get the top-level parent of a given term?
Instead of showing all tagged terms, I only want to show tagged terms' top-level parents.

So if these are my selected terms, I only want to show Breakfast, Lunch and Dinner.

x BREAKFAST
x Cereal
x Eggs
LUNCH
Hamburger
x Pizza
DINNER
Fish
Bass
x Salmon
Trout
Lasagna

The code I have is here, but it gives an error where specified in the comment. To invoke it I am using echo hey_top_parents( 'taxonomyname' ); in a WP Query loop.

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 /path/to/plugin on line 675" */

}
return $r;

}

Answers (2)

2011-08-04

Ivaylo Draganov answers:

Hello,

That function contained some errors and shortcomings. Here's a fixed version of it:
[[LINK href="http://pastebin.com/UfYYkQWh"]]http://pastebin.com/UfYYkQWh[[/LINK]]

I've tested it with categories and it works. It returns the parent terms as an unordered list, but you can change that if you wish.

Cheers!


Ivaylo Draganov comments:

I see you've updated your question. Did you already try the solution that I've proposed?


web559 comments:

I am about to try it right now... thanks!


web559 comments:

Works great. Thanks for the fixes and for documenting the code.

2011-08-04

Lee Willis answers:

Your function to get the top most parent should be amended as follows:

function get_term_top_most_parent($term_id, $taxonomy){

$term = get_term_by( 'id', $term_id, $taxonomy);

if ( $term->parent != 0 ) {
return get_term_top_most_parent ( $term->parent, $taxonomy )
} else {
return $term;
}

}


Also, further down your code:
$top_parent_terms[] = $top_parent;
should be:
$top_parent_terms[] = $top_parent->ID;


web559 comments:

I still get the same error for the same line. I believe I have added all of your changes correctly-- see https://gist.github.com/1125575