Return only top-level custom taxonomy term associated with posts in the loop (4 posts)

  1. atburi
    Posted 3 years ago #


    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:

    $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) {
    		 $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/.


  2. atburi
    Posted 3 years ago #

    just moving the post to the top again...

  3. stratocentric
    Posted 2 years ago #

  4. atburi
    Posted 2 years ago #

    with get_terms, I can limit the results to show just one term?

    I will check - thanks.

Topic Closed

This topic has been closed to new replies.

About this Topic