Quantcast
Viewing all articles
Browse latest Browse all 134857

Alex on "Return only top-level custom taxonomy term associated with posts in the loop"

Hello,

I have a loop of custom post types and I want to return the custom (hierarchical) taxonomy terms (with a link to the term archive) that are associated with each post in the loop.

Some posts have multiple terms, and in such cases I only want to return the top-level term for that post.

I've searched through the forums and tried numerous variations of 'get_terms', 'get_the_terms', and 'wp_get_object_terms'.

They each work to get the terms and the term links, but I haven't figured out how to restrict them to returning only the top-level term.

For example:

<?php
$terms = get_the_terms( $post->ID, 'countries' );

$count = count($terms); $i=0;
	if ($count > 0) {
	    $cape_list = '<p class="my_term-archive">';
	    foreach ($terms as $term) {
                 $i++;
		 $term_list .= '<a href="'.get_term_link($term->slug, 'countries').'" title="' . sprintf(__('View all partner requests for %s', 'my_localization_domain'), $term->name) . '">' . $term->name . '</a>';
		  if ($count != $i) $term_list .= ' · '; else $term_list .= '</p>';
	 }
        echo $term_list;
}
?>

works fine - but I want this to return only the top-level term.

Any ideas? The loop I am referring to is the list of posts on the home page of http://trekkingpartners.com/.

Thanks!
Alex


Viewing all articles
Browse latest Browse all 134857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>